【问题标题】:How to create new data types on Lua code?如何在 Lua 代码上创建新的数据类型?
【发布时间】:2013-03-05 07:27:10
【问题描述】:

我在网上搜索过,但没有教程让我真正清楚,所以我需要对此进行简要说明:

我想为 lua(在 C 语言编译器中)创建新的数据类型,以创建如下值:

pos1 = Vector3.new(5, 5, 4) --Represents 3D position

pos2 = CFrame.new(4, 2, 1) * CFrame.Angles(math.rad(40), math.rad(20), math.rad(5)) --Represents 3D position AND rotation

这些是我可以在名为 Roblox 的游戏引擎上通常使用的一些代码。我想重新创建它们以便在 Roblox 之外使用。

【问题讨论】:

  • 没有关于如何创建对象的“简要”说明。在 Lua 中有很多方法可以做到这一点,这取决于你对它的重视程度。
  • 为什么不对新数据类型使用普通的 Lua 表(可以从 C 和 Lua 完全访问)?

标签: lua roblox


【解决方案1】:
local Vector3 = {} 
setmetatable(Vector3,{
    __index = Vector3;
    __add = function(a,b) return Vector3:new(a.x+b.x,a.y+b.y,a.z+b.z); end;
    __tostring = function(a) return "("..a.x..','..a.y..','..a.z..")" end
}); --this metatable defines the overloads for tables with this metatable
function Vector3:new(x,y,z) --Vector3 is implicitly assigned to a variable self
    return setmetatable({x=x or 0,y=y or 0,z=z or 0},getmetatable(self)); #create a new table and give it the metatable of Vector3
end 

Vec1 = Vector3:new(1,2,3)
Vec2 = Vector3:new(0,1,1)
print(Vec1+Vec2)

输出

(1,3,4)
> 

【讨论】:

    【解决方案2】:

    metatables 和 loadstring 是我以与此类似的方式得出的结论:

    loadstring([=[function ]=] .. customtype .. [=[.new(...)
    return loadstring( [[function() return setmetatable( {...} , {__index = function() return ]] .. ... .. [[ ) end )() end]] ]=] )()
    

    这只是我的意思的要点。很抱歉,它不够整洁和完美,但至少它可以继续下去(我昨晚没睡多少觉)。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2011-11-22
      • 2021-03-22
      • 1970-01-01
      • 2011-09-09
      • 2020-04-24
      • 1970-01-01
      • 2021-12-18
      • 2016-06-23
      相关资源
      最近更新 更多