Search code examples
classmethodslualua-table

how to create Lua methods that work with tables automatically


In Lua, I see some methods such as the string and io class that allows you to call the method from the table automatically, without the need to instantiate an object for this, example:

the following code:

local tb = {"Hello", "World!"}

table.concat(tb)

can be written like this:

local tb = {"Hello", "World!"}

tb:concat()

I tried to create a method that could do the same thing:

local tst = {}

function tst:test()
     print("test")
end

but the following code does not work:

local tb = {"Hello", "World!"}

tb:test()

only if I inform the code that tb = tst:

local tb = tst

tb:test()

my question is, there any way for me to create methods that work with a string, or a table automatically as in the second example without the need to instantiate the class? like, calling my table as a table:MyMethod()


Solution

  • I'm not sure if this answers your original question, but maybe answering your question from the comments will help explain things.

    The following code is an example of how you might instantiate a table with some methods.

    local function makeArray()
      local a = {}
      setmetatable(a, {__index = table})
      return a
    end
    

    The setmetatable call basically makes all the functions from the table library accessible from the new array. This is useful, because all the table functions except pack expect an array as their first argument.

    Vanilla Lua does something similar for strings. All strings have {__index = string} as their metatable.