2

I've searched the web, but no tutorial really made it clear to me, so I need a brief explanation on this:

I want to create new data types for lua (in the C language compiler) for creating values like:

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

These are some lines I could ordinary use on a game engine called Roblox. I want to recreate them for using outside Roblox.

2
  • 1
    There's no "brief" explanation for how to create objects. There are many ways of doing so in Lua, depending on how serious you are about it. Commented Mar 16, 2013 at 17:02
  • 1
    Why not using ordinary Lua tables (which are fully accessible from both C and Lua) for your new data types? Commented Mar 16, 2013 at 17:27

2 Answers 2

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)

Outputs

(1,3,4)
> 
Sign up to request clarification or add additional context in comments.

Comments

0

metatables and loadstring are the closes i have come to it in a similar way to this:

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

This is just the gist of what i mean. Im sorry that its not neat and perfect, but at least its something to go on (i did not sleep much last night).

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.