Thanks
This is a read-only snapshot of the ComputerCraft forums,
taken in April 2020.
[Lua] Metatables
Started by anonimo182, 24 January 2013 - 12:53 PMPosted 24 January 2013 - 01:53 PM
What are the metatables? Are they useful? Why to use them?Anything more to learn from them?
Thanks
Thanks
Posted 24 January 2013 - 01:56 PM
Tables, yes, Cause, Yes
You're Welcome :)/>
To be honest you can probably learn a lot more in the Lua Documentation, that's always the first place to look for advanced Lua stuff, Here I'll grab the link.
http://pgl.yoyo.org/.../2.8+Metatables
http://www.youtube.com/watch?v=CYxMfVy5W00
You're Welcome :)/>
To be honest you can probably learn a lot more in the Lua Documentation, that's always the first place to look for advanced Lua stuff, Here I'll grab the link.
http://pgl.yoyo.org/.../2.8+Metatables
http://www.youtube.com/watch?v=CYxMfVy5W00
Posted 24 January 2013 - 01:58 PM
Posted 24 January 2013 - 01:59 PM
Thanks!
Posted 24 January 2013 - 02:01 PM
lua.org has so much nicer formatting than yoyo! <3
Posted 24 January 2013 - 02:02 PM
indeed the PIL is nice… I like how it breaks it up into small sections for ppl…lua.org has so much nicer formatting than yoyo! <3
Posted 24 January 2013 - 02:57 PM
metatables are pretty much only useful for OOP, but when you get any deeper than your toes into OOP, they become essential in Lua.
Posted 24 January 2013 - 03:06 PM
Metatables can also be used for sorcery!
Using the __index and __newindex, You could make a table represent your file system.
Not tested, and may have bugs. But the concept is excuse me, F'in awesome!
files["/startup"] then returns content, and you can set the content of the file with
files["/startup"] = 'print"ALL THE THINGS!"'
Using the __index and __newindex, You could make a table represent your file system.
local fs_mt = {}
fs_mt.__index = function(t, k)
if fs.exists(k) and not fs.isDir(k) then
local h = fs.open(k, "r")
if not h then return nil end
local v = h.readAll()
h.closeAl()
return v
else
return nil
end
end
fs_mt.__newindex = function(t,k,v)
local h = fs.open(k, "w")
if not h then return nil end
h.write(v)
h.close()
end
files = {}
setmetatable(files, fs_mt)
Not tested, and may have bugs. But the concept is excuse me, F'in awesome!
files["/startup"] then returns content, and you can set the content of the file with
files["/startup"] = 'print"ALL THE THINGS!"'