如何将Lua变量直接映射到C变量?
我正在使用Lua在C中使用游戏引擎来定义NPC.
我可以像这样定义一个原型NPC: orc = { name = "Generic Orc",health = 100 } function orc:onIdle() print("Orc idles...") end 然后使用entitySpawn(orc)生成“Orc”的实例.这是一个C函数,它从给定的表中读取健康和名称等值,在C中使用给定的值创建一个Entity对象,另外为特定的NPC创建一个Lua表. 现在,我想在Lua中的orc.health变量和C中相应的Entity对象的mHealth成员变量之间建立直接连接,因此我可以在Lua中分配一个值并立即在C中使用它,反之亦然. 这甚至可能吗?或者我是否必须使用setter / getter函数?我已经看了一下light userdata并且已经到了在Lua中存储指向C变量的指针,但无法分配值. 解决方法
这个有可能.我假设entitySpawn返回C为实体创建的表.我还假设您可以从C中公开一个函数,该函数接受实体的表并返回当前的运行状况,类似于设置. (您可以使用指向C对象的light userdata指针作为此表的成员来实现此目的.)
所以丑陋的方式看起来像这样: local myOrc = entitySpawn(orc) local curHealth = getEntityHealth(myOrc) setEntityHealth(myOrc,curHealth + 10) 为了使这个更漂亮,我们可以与metatables有一些乐趣.首先,我们将为我们关心的所有属性设置访问器. entityGetters = { health = getEntityHealth,-- ... } entitySetters = { health = setEntityHealth,-- ... } 然后我们将创建一个使用这些函数来处理属性分配的metatable. entityMetatable = {} function entityMetatable:__index(key) local getter = entityGetters[key] if getter then return getter(self) else return nil end end function entityMetable:__newindex(key,value) local setter = entitySetters[key] if setter then return setter(self,value) end end 现在你需要让entitySpawn分配metatable.您可以使用 int entitySpawn(lua_State* L) { // ... // assuming that the returned table is on top of the stack lua_getglobal(L,"entityMetatable"); lua_setmetatable(L,-2); return 1; } 现在你可以用很好的方式编写它: local myOrc = entitySpawn(orc) myOrc.health = myOrc.health + 10 请注意,这要求entitySpawn返回的表没有设置健康属性.如果确实如此,则永远不会为该属性咨询metatable. 您可以在C中而不是Lua中创建entityGetters,entitySetters和entityMetatable表,以及__index和__newindex元方法,如果您感觉更干净,但总体思路是相同的. (编辑:李大同) 【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容! |