c - 卢阿 :new from C API

标签 c oop scripting lua lua-api

我正在为我的游戏引擎开发脚本层。目前我正在使用脚本作为类,向名为 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/

相关文章:

c# - 了解用于 C# 翻译的 C 函数

C++(看似)随机编译器错误

java - 面向对象编程 : adding features on the fly

java - 当订阅者需要主消息类型的子类时,观察者模式就不够用了,替代方案?

Python Pygame : error when using python. 对象中的draw.rect

C:内联关键字值得吗?

c - 如何从 C 中的 float 中提取有偏差的指数?

Abaqus 的 Python 脚本

python - 将脚本语言嵌入到游戏引擎的编程语言中的目的是什么?

python - 防止在 Python 中导入