Norbert Ozdoba
Norbert Ozdoba

Reputation: 525

Lua - C++ Integration: Calling function in table from C++

I am not a Lua expert, but I've red some articles to understand how does it work. However I have problem with calling lua functions that belongs to a table from C++.

On example described below I am trying to call foo:bar from code. Call succeeded. However parameter "a" is nil ( return value is correct - when I'll change return value to for example 10, then it shows proper result )

Did I miss something during pushing function arguments to script ?

lua_State* state = LuaIntegration->GetLuaState();
lua_getglobal(state, "foo");
if(lua_istable(state,  lua_gettop(state))) { 
    lua_getfield(state, -1, "bar");
    if(lua_isfunction(state, lua_gettop(state))) { 
        lua_pushinteger(state, 0);
        if (lua_pcall(state, 1, 1, 0) != 0) {
            ErrorMessage = lua_tostring(state, -1);
        }
        ReturnValue = lua_tointeger(state, -1);
    }
}

It calls function in lua:

foo = base_foo:new()

function foo:new(o)
      o = o or {}
      setmetatable(o, self)
      self.__index = self
      return o
end

function foo:bar(a) 
  if a==10 then
    return a
  end
  return 0
end

Upvotes: 2

Views: 590

Answers (1)

Etan Reisner
Etan Reisner

Reputation: 80921

You forgot the sugar in your C++ call.

If you read the Function Calls section of the lua manual you'll see that

A call v:name(args) is syntactic sugar for v.name(v,args), except that v is evaluated only once.

Which means that base_foo:new() is really just base_foo.new(base_foo).

That's what you are missing in your C++ call.

You need to pass the table as the first argument to the function when you call it.

Upvotes: 3

Related Questions