2013-03-16 70 views
2

我在网上搜索,但没有真正的教程就明确给我,所以我需要在此简要说明:如何在Lua代码上创建新的数据类型?

我想为LUA创建新的数据类型(在Ç语言编译器)像创造价值:

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。

+1

关于如何创建对象没有“简要”解释。在Lua中有很多方法可以这样做,这取决于你对此有多认真。 – 2013-03-16 17:02:48

+1

为什么不为你的新数据类型使用普通的Lua表(可以从C和Lua完全访问)? – 2013-03-16 17:27:17

回答

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) 
> 
0

元表和加载链是我今天来给它以同样的方式向这个关闭:

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

这只是我的意思的要点。对不起,它不完美和完美,但至少有一些事情要继续(昨晚我没有睡太多)。

相关问题