4

My goal is to simply call a table function from C++ that uses 'self' inside of the function to access fields and functions of that table. I keep getting the lovely 'attempt to call a nill value (local self)' on the line that has 'self.name'. Below is my Lua script.

Foo = { name = 'Foo' }

function Foo:OnUpdate()
  print('In OnUpdate in Lua')
  print(self.name)
end

Below is my C++ code (ignoring any error handling for now).

lua_State* L = luaL_newstate();
luaL_openlibs(L);
luaL_dofile(L, "foo.lua");
lua_getglobal(L, "Foo");
lua_getfield(L, -1, "OnUpdate");
lua_pcall(L, 0, 0, 0);

When 'lua_pcall' is called, I see 'In OnUpdate in Lua' in the CLI, but never 'Foo'. If I check the error from 'lua_pcall' I get the error message mentioned above. Am I missing a certain Lua C API function prior to calling 'lua_pcall'? I am aware of the '.' vs. ':' in lua for utilizing 'self'. If I add a call in the Lua script like 'Foo:Update()', everything works perfectly. This has got me stumped.

1 Answer 1

4

You need to send the value of Foo as the first argument. So, do

lua_pushvalue(L, -2);
lua_pcall(L, 1, 0, 0);
Sign up to request clarification or add additional context in comments.

1 Comment

Beautiful! Thank you so much!

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.