Userdata

From Legacy Roblox Wiki
Revision as of 05:09, 9 August 2010 by >GoldenUrg (fixed description; provided alternative example)
Jump to navigationJump to search

A userdata is the type Lua uses for data structures in the underlying C program. There are no native Lua functions for handling those types, they must be handled via metatable. All Roblox objects are userdata Lua type.

Advanced

You can create a new userdata by passing true to the undocumented newproxy function. This userdata cannot be used for anything other than invoking functions via its metatable.

WARNING: newproxy is temporarily disabled due to maintenance on _G

local NewUserData = newproxy(true) -- New userdata; Returns an empty metatable
getmetatable(NewUserData).__index = {Name = "Foo", FooValue = "EPIC"} -- index MetaMethod
print(type(NewUserData), NewUserData.Name, NewUserData.FooValue)

In the output window, you should see

userdata Foo EPIC

An equivalent functionality can be achieved in pure Lua:

function newproxy( src )
local obj = {}
local mt
if src == true then
   mt = {}
elseif src then
   mt = getmetatable( src )
end
setmetatable( obj, mt )
return obj
end

local NewUserData = newproxy(true) -- New userdata; Returns an empty metatable
getmetatable(NewUserData).__index = {Name = "Foo", FooValue = "EPIC"} -- index MetaMethod
print(type(NewUserData), NewUserData.Name, NewUserData.FooValue)

Output:

table Foo EPIC