Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/lua/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在Lua代码上创建新的数据类型?_Lua_Roblox - Fatal编程技术网

如何在Lua代码上创建新的数据类型?

如何在Lua代码上创建新的数据类型?,lua,roblox,Lua,Roblox,我已经在网上搜索过了,但没有任何教程真正让我明白,因此我需要对此进行简要说明: 我想为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

我已经在网上搜索过了,但没有任何教程真正让我明白,因此我需要对此进行简要说明:

我想为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外部使用

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

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

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

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

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