Why can we do str:split(",") but not tab:insert(val)?

Viewed 60

We can do either string.split("1,2,3",",") or ("1,2,3"):split(",") and receive the same result.

However tab = {} table.insert(tab, "hi") works while tab = {} tab:insert("hi") throws the error

tab = {} tab:insert("hi"):1: attempt to call a nil value

This seems inconsistent, am I doing something wrong or is there a good reason why calling methods in Lua is different?

Thank you,

1 Answers

It's because strings have a default metatable in Lua, but tables do not. You can set the metatable yourself:

local tab = setmetatable({}, {__index = table})
tab:insert("hi")
print(#tab)

This should print 1. See 2.4 and 6.4 sections in the Lua Manual for details.

Related