This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
anonimo182's profile picture

[Lua] Metatables

Started by anonimo182, 24 January 2013 - 12:53 PM
anonimo182 #1
Posted 24 January 2013 - 01:53 PM
What are the metatables? Are they useful? Why to use them?Anything more to learn from them?

Thanks
NeverCast #2
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
theoriginalbit #3
Posted 24 January 2013 - 01:58 PM
have a read of this chapter http://www.lua.org/pil/13.html

Common usage is for objects in Lua.
anonimo182 #4
Posted 24 January 2013 - 01:59 PM
Thanks!
NeverCast #5
Posted 24 January 2013 - 02:01 PM
lua.org has so much nicer formatting than yoyo! <3
theoriginalbit #6
Posted 24 January 2013 - 02:02 PM
lua.org has so much nicer formatting than yoyo! <3
indeed the PIL is nice… I like how it breaks it up into small sections for ppl…
tesla1889 #7
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.
NeverCast #8
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.


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!"'