我正在为我的游戏引擎开发脚本层。目前我正在使用脚本作为类,向名为 new 的“表”添加一个方法。该函数基本上创建了该类的实例化副本。当需要脚本实例时,我从 C API 调用此函数。
function PlayerController:new(o)
print('A new instance of the PlayerController has been created');
o = o or {}
setmetatable(o, self)
self.__index = self
return o
end
我的问题是:如何获取上述 Lua 代码,并将其移至 C 中,这样就不需要将其添加到我为此系统编写的每个脚本文件中?
最佳答案
您可能需要创建一个类声明函数来为您执行此操作。这是一个完整的“helper.lua”文件:
local lib = {type = 'helper'}
local CALL_TO_NEW = {__call = function(lib, ...) return lib.new(...) end}
function lib.class(class_name, tbl)
local lib = tbl or {}
lib.type = class_name
lib.__index = lib
-- Default "new" method
function lib.new()
return setmetatable({}, lib)
end
-- Enable foo.Bar() instead of foo.Bar.new()
return setmetatable(lib, CALL_TO_NEW)
end
return lib
使用示例:
local helper = require 'helper'
local lib = helper.class 'foo.Bar'
-- optional new function if there needs to be some argument handling
function lib.new(args)
local self = {}
-- ...
return setmetatable(self, lib)
end
return lib
lub.class
这是一个现实世界的最小类声明和设置系统。它被用在许多 luarocks 中,例如 xml、yaml、dub 等:
关于c - 卢阿 :new from C API,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/24252122/