• Announcement: Lua.org now officially recommends this forum as a meeting place for the Lua community

How come there are no table methods? (1 Viewer)

vsajip

Newcomer
Joined
Feb 7, 2022
Messages
1
Reaction score
0
Website
www.red-dove.com
For example, if you want to append an item item to a table t, you do

Code:
table.insert(t, item)

Why can you not do the following?

Code:
t:insert(item)

I mean I see that a basic table has no metatable, so I guess that's why - what I mean to ask is, why is that the case? Ditto for the other functions like pack, unpack etc.
 
Last edited:

GavinW

Newcomer
Creator of RiscLua
Joined
Oct 21, 2020
Messages
54
Reaction score
20
Age
83
Location
UK
Website
www.wra1th.plus.com
Lua:
t = setmetatable ({ }, { __index = table })
t:insert "hello"
print (t[1]) --> hello
My guess is that tables, being the sole datatype in Lua, are left in their pristine unmetatabled form so as not to foist upon users what they may not want. If only supermarkets would follow this principle and cease to adulterate their goods with all manner of spices and additives that I do not want - dill on salmon, mustard in scotch eggs, too much sugar in desserts - an endless list to make the gorge rise.
 
Last edited:

stetre

Member
Rank: II
Joined
Jan 8, 2020
Messages
103
Reaction score
58
Location
Italy
Website
github.com
According to the manual "By default, a value has no metatable, but the string library sets a metatable for the string type (see §6.4).".

The table.insert function and its siblings that act on tables are just that: functions, not methods. You could turn them easily into methods for a specific table, if you want to, by just doing this:

Lua:
t = {}
setmetatable(t, {__index = table})
-- now table.insert() is also available as a method for t:
t:insert(123) -- same as table.insert(t, 123)

This is not done by default for tables because (my guess) this would make metaprogramming more difficult, with no real benefits other than an alternative way to call functions that are already available.

It is done for strings (also my guess) because strings are not meant to be 'casted' to custom types by manipulating their metatables (which you cannot do, IIRC), so it is safe to give them a default metatable whose sole purpose is to present the string.xxx() functions in an alternative sugary way.
 
Top