Jump to content




[Lua] Metatables


  • You cannot reply to this topic
7 replies to this topic

#1 anonimo182

  • Members
  • 252 posts
  • LocationIn the universe

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

#2 NeverCast

  • Members
  • 400 posts
  • LocationChristchurch, New Zealand

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


#3 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

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.

#4 anonimo182

  • Members
  • 252 posts
  • LocationIn the universe

Posted 24 January 2013 - 01:59 PM

Thanks!

#5 NeverCast

  • Members
  • 400 posts
  • LocationChristchurch, New Zealand

Posted 24 January 2013 - 02:01 PM

lua.org has so much nicer formatting than yoyo! <3

#6 theoriginalbit

    Semi-Professional ComputerCrafter

  • Moderators
  • 7,332 posts
  • LocationAustralia

Posted 24 January 2013 - 02:02 PM

View PostNeverCast, on 24 January 2013 - 02:01 PM, said:

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...

#7 tesla1889

  • Members
  • 351 posts
  • LocationSt. Petersburg

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.

#8 NeverCast

  • Members
  • 400 posts
  • LocationChristchurch, New Zealand

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





2 user(s) are reading this topic

0 members, 2 guests, 0 anonymous users