Userdata: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Blocco
No edit summary
>GoldenUrg
fixed description; provided alternative example
Line 1: Line 1:
A userdata is just another way to represent data. It is very similar to a [[Metatables|metatable]]. You can create a new userdata by passing true to the newproxy function.
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 [[Metatables|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.  


<big><span style="color:#ff0000;">WARNING: newproxy is temporarily disabled due to maintenance on _G</span></big>
<big><span style="color:#ff0000;">WARNING: newproxy is temporarily disabled due to maintenance on _G</span></big>
Line 12: Line 15:
userdata Foo EPIC
userdata Foo EPIC
</pre>
</pre>
An equivalent functionality can be achieved in pure Lua:
<pre>
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)
</pre>
Output:
<pre>
table Foo EPIC
</pre>
[[Category:Data Types]]
[[Category:Data Types]]

Revision as of 05:09, 9 August 2010

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