Forum

> > Off Topic > Table:Method Self Methods (string:method)
Forums overviewOff Topic overviewLog in to reply

English Table:Method Self Methods (string:method)

1 reply
To the start Previous 1 Next To the start

old Table:Method Self Methods (string:method)

Apache uwu
User Off Offline

Quote
1
2
3
4
5
6
function string:print()
	print(self)
end
a="12345"
a:print()
--prints "12345"

Works fine

1
2
3
4
5
6
7
8
9
function table:print()
	for _,item in ipairs(self) do
		print(self)
	end
end

a={1,2,3,4,5}
a:print()
--returns method not found

Fails. And yes I have tried changing the method name.

I realize this requires metatables, but I have no idea what those are.

old Re: Table:Method Self Methods (string:method)

Flacko
User Off Offline

Quote
It's because a string's metatable is the string table by default.
While a just created table doesn't have any metatable yet.

Try
1
2
3
4
5
6
table.__index = function(t,k)
	return table[k] or t[k]
end
t = {'one',2,'III',"4!"}
setmetatable(t,table)
t:print()

A metatable defines a table's behaviour through metamethods like (__add, __sub, __mul, __div, etc) for more info:
http://www.lua.org/manual/5.1/manual.html#2.8

metatable:method works fine if you specify the __index metamethod to look for your custom method in the metatable (otherwise, Lua will try to look for the print() function inside your instance table)
To the start Previous 1 Next To the start
Log in to replyOff Topic overviewForums overview