【问题标题】:Lua C API create table from tableLua C API 从表创建表
【发布时间】:2011-10-20 05:45:14
【问题描述】:

目前我在 lua 中有一些类似于 OOP 使用表的东西。

TCharacterController = {}
TCharacterController.speed = 10.0
TCharacterController.axis = "x"

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

function TCharacterController:update()
    --this is a function that is called by the C application
end

概念是我将创建一个子对象

ScriptObj = TCharacterController:new()

对于附加到我的应用程序中的对象的每个脚本实例(这是针对游戏的)。所以我有一个实体层,所有实体都可以附加一个 ScriptObj。我的想法是 Script 实际上是一个类,它也为它所附加的每个实体实例化。

我的问题是,如何使用 C API 实例化 TCharacterController 的实例?

【问题讨论】:

    标签: c lua


    【解决方案1】:

    由于 new 使用的是自引用语法糖,所以您需要将 self 作为第一个 arg 传递,剩下的只是一个查表的函数调用:

    lua_getglobal(L, "TCharacterController"); /* get the table */
    lua_getfield(L, -1, "new");  /* get the function from the table */
    lua_insert(L, -2); /* move new up a position so self is the first arg */
    lua_pcall(L, 1, 1); /* call it, the returned table is left on the stack */
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-03-20
      • 2021-10-05
      • 2010-12-10
      • 2016-10-18
      • 2011-02-17
      • 1970-01-01
      • 2011-06-29
      • 2014-06-18
      相关资源
      最近更新 更多