Userdata: Difference between revisions

From Legacy Roblox Wiki
Jump to navigationJump to search
>Sncplay42
Yep, it's back.
>Camoy
better format?
Line 1: Line 1:
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.
__TOC__


== Advanced ==
==What is a Userdata?==
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]]. All Roblox objects and events are userdata Lua type.
 
==Using Userdatas==
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.  
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.  


<pre>
{{Example|<pre>
local NewUserData = newproxy(true) -- New userdata; Returns an empty metatable
local ud = newproxy(true) -- new userdata with an empty metatable
getmetatable(NewUserData).__index = {Name = "Foo", FooValue = "EPIC"} -- index MetaMethod
getmetatable(ud).__index = {Foo = "Bar"} -- index metamethod
print(type(NewUserData), NewUserData.Name, NewUserData.FooValue)
print(type(ud), ud.Foo)
</pre>
 
In the output window, you should see
<pre>
userdata Foo EPIC
</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:
Output:
<pre>
userdata: 0x631fc8 Bar
table Foo EPIC
</pre>}}
</pre>


[[Category:Data Types]]
[[Category:Data Types]]

Revision as of 13:58, 31 October 2010

What is a Userdata?

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. All Roblox objects and events are userdata Lua type.

Using Userdatas

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.

Example
local ud = newproxy(true) -- new userdata with an empty metatable
getmetatable(ud).__index = {Foo = "Bar"} -- index metamethod
print(type(ud), ud.Foo)

Output:
userdata: 0x631fc8	Bar