从C++调用Lua函数,缺少参数。

我用 C++ 调用 Lua 函数时遇到了奇怪的问题。

在 Lua 中我有:

Player =
{
    Number = 0.43,
    Text = "SomeText",
}

function Player:Func(a, b)
    return (a * b);
end

在调用 lua_pcall 之前,我堆栈中的内容如下:

table

function

3

4

我使用以下语句调用该函数:

lua_pcall(L, 2, 1, 0)

然后我从 Lua 中得到以下错误:

attempt to perform arithmetic on local 'b' (a nil value)

当我把 Lua 脚本中的

return (a * b);

改为

return a;

时,就没有错误了,但是从 lua_tonumber(L, -1); 得到的值是 4(我的 C:/ 中的第二个参数),这表明我的第二个 C++ 参数在 Lua 中是第一个。

您知道我在代码中犯了什么错误吗?

我构建堆栈的方式如下:

lua_getglobal (L, "Player");
lua_pushstring(L, "Func");
lua_gettable(L, -2);
lua_pushnumber(L, 3.0);
lua_pushnumber(L, 4.0);
点赞
用户1737
用户1737

Ben's comment is the key - Read the Object-oriented programming section in "Programming In Lua", page 150.

http://www.lua.org/pil/16.html

The effect of the colon is to add an extra hidden parameter in a method definition and to add an extra argument in a method call.

所以你需要将一个“Account”对象作为第一个参数推入,或者更容易的方式是将 function Player:Func(a, b) 更改为 function Player.Func(a, b)

2012-05-27 21:35:24