当我进入一个新文件时,Luabind对象消失了。

我正在使用Luabind将我的 Lua 脚本绑定到我的 C++ 引擎上(它使用 lua 5.1.4)。

我添加了一个名为“controller.lua”的新的 Lua 脚本,我的实体脚本“cat.lua”会引用并使用它。一旦 C++ 调用了“Update”方法,就全交给 Lua 处理了。

但是,一旦我尝试将我的绑定的 C++ 方法传递给新的脚本文件,感觉所有与该 C++ 对象绑定的内容都消失了。我收到以下错误:

Expression: scripts/controller.lua:5(method MoveUp) scripts/controller.lua:5: attempt to call method 'GetComponent' (a nil value)

这是一些 C++ 片段:

// Definitions
module(luaState)
[
    class_<Entity>("Entity")
        .def("GetComponent", &Entity::GetComponent)
    class_<Component>("Component")
        .enum_("eComponentTypes")
        [
            value("Steering", kComponentType_Steering)
        ],
    class_<SteeringComponent>("SteeringComponent")
];

// The script components update
void ScriptComponent::Update() {
    const Entity* owner = this.GetOwner();
    mLuaDataTable["Update"](owner); // 执行脚本 Cat.lua 上的 Update 函数
}

被 C++ 调用的实体代码(当它执行时会将 Cat 表返回给 C++):

-- Cat.lua
local controller = loadfile("scripts/controller.lua")
local Cat = {}

function Cat.Update(entity)
    steeringComponent = entity:GetComponent(Component.Steering) -- 正常工作
    controller:MoveUp(entity)
end

return Cat

以及控制器:

--controller.lua
local up = vec2(0.0, 1.0)
local Controller = {}

function Controller.MoveUp(entity)
    steeringComponent = entity:GetComponent(Component.Steering) -- 失败
end

return Controller

加分题: 当我做出无法使用的更改(如在任何地方只是随意加了一个字符),控制器库加载为 nil,没有警告。有没有什么方法可以使它抛出警告?

有没有更好的方法可以“链接”到其他 Lua 文件,例如我正在处理 Controller 的方式?

点赞
用户1072711
用户1072711

感谢 Freenode 聊天室上的 ToxicFrog 帮助我解决了这个问题。

基本上:我之前这样调用控制器的 MoveUp 函数:

controller:MoveUp(entity)

这当然会被翻译成

controller.MoveUp(controller, entity)

而函数定义是这样的:

function Controller.MoveUp(entity)

这个 "entity" 被解释成第一个参数 controller,而实际上的 entity 就被规范抛弃了。

http://lua-users.org/wiki/ObjectOrientationTutorial

2014-01-22 02:16:47