Voting

Category

real language

Bookmarking

Del.icio.us Digg Diigo DZone Earthlink Google Kick.ie
Windows Live LookLater Ma.gnolia Reddit Rojo StumbleUpon Technorati

Support Us

Language LUA

(Examples of metatables in lua 5.1)

Date:06/07/07
Author:Peter Cawley
URL:n/a
Comments:0
Info:http://www.lua.org/
Score: (3.09 in 22 votes)
phrase  = "Take one down and pass it around,"
none    = "No more bottles of beer"
justone = "1 bottle of beer"

bottles = setmetatable({0,
	drink = {
		phrase .. "\n" .. none .. " on the wall,",
		"Go to the store and buy some more!"
	}},{
	__index = function(crate,num)
		crate[num] = nil
		print(crate[num] .. " on the wall,")
		print(crate[num] .. ",")
		print(phrase)
		crate[num] = crate[num-1]
		return justone .. " on the wall,\n"
	end, __newindex = function(crate,num,drink)
		rawset(crate,num,drink or (num .. " bottles of beer"))
		if rawget(crate,num+1) then
			print(crate[num] .. " on the wall,\n")
		end
	end, __call = function()
		return ipairs{justone, none}
	end}
)

print(bottles[99])

for it, beer in bottles() do
	print(beer .. " on the wall,")
	print(beer .. ",")
	print(bottles.drink[it])
	print ""
end

Download Source | Write Comment

Alternative Versions

VersionAuthorDateCommentsRate
original versionPhilippe Lhoste04/20/051
5.1, bottledPeter Cawley04/19/090
version 5.xchill07/10/052

Comments

Download Source | Write Comment

Add Comment

Please provide a value for the fields Name, Comment and Security Code.
This is a gravatar-friendly website.
E-mail addresses will never be shown.
Enter your e-mail address to use your gravatar.

Please don't post large portions of code here! Use the form to submit new examples or updates instead!

Name:

eMail:

URL:

Security Code:
  
Comment: