Lua How do I create a custom function that can be used for variables?

With methods like io.close (), you can use it like this:

file:close()

      

Is there a way to create a custom function that works exactly like this where you can call it a variable?

For me, I am trying to use it to split arguments from a text file using string.find to find spaces

So in a text file it looks like

this is some input

      

And the readArgs () function should return the entire row in the table using args [1] = "So", args [2] = "in", args [3] = "the", etc. after the call the line

function readFile(file)
    local lines = {}
    assert(io.open(file), "Invalid or missing file")
    local f = io.open(file)
    for line in f:lines() do
        lines[#lines+1] = line
    end
    return lines
end

function readArgs(line) -- This is the function. Preferably call it on the string line
    --Some code here
end

      

+3


source to share


1 answer


Based on your description it looks like you are after something similar to this syntax:

local lines = readFile(file)
lines:readArgs(1) -- parse first line {"this", "is", "some", "input"}

      

Metatables can help with this:

local mt = { __index = {} }
function mt.__index.readArgs(self, linenum)
  if not self[linenum] then return nil end

  local args = {}
  for each in self[linenum]:gmatch "[^ ]+" do
    table.insert(args, each)
  end
  return args
end

      

You will need to make minor changes to readFile

and attach this meta tag to the returned one lines

:

function readFile(file)
  -- ...
  return setmetatable(lines, mt)
end

      

Edit . To answer OP's comment, the call looks like this:



lines:readArgs(1)

      

is just syntactic sugar for:

lines.readArgs(lines, 1)

      

When the lua virtual machine executes the above line, the following happens:

  • Does the table have a lines

    key readArgs

    ?
  • If so, use the rest of the instructions as usual.
  • If not, does the lines

    meta index have .__? In this case it is, so the function assigned is used __index.readArgs

    .
  • readArgs

    is now called with the above options: self

    = lines, linenum

    = 1

Nothing fancy here self

, it's just a regular parameter; you can call it whatever you want.

+3


source







All Articles