【问题标题】:Lua How to create custom function that can be used on variables?Lua 如何创建可用于变量的自定义函数?
【发布时间】:2015-02-05 02:08:36
【问题描述】:

使用 io.close() 之类的方法,您可以像这样使用它:

file:close()

有没有办法创建一个像这样工作的自定义函数,你可以在变量上调用它?

对我来说,我试图通过使用 string.find 来查找空格,从而将参数与文本文件分开

所以在文本文件中看起来像

this is some input

并且 readArgs() 函数应该返回表中的整行,其中 args[1] = "So", args[2] = "in", args[3] = "the" 等在被调用后线

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

【问题讨论】:

  • 所以,澄清一下,你想做的是能够打电话给someStringVariable:readArgs()?
  • 是的。也许在 string:readArgs() 之类的东西上调用它,然后让它返回一个参数表或其他东西
  • 术语:函数有值作为参数;不是变量。 : 的 LHS 是一个表达式。

标签: function variables lua


【解决方案1】:

根据您的描述,听起来您正在寻找类似于此语法的内容:

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

元表可以帮助解决这个问题:

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

您必须对您的 readFile 进行轻微更改,并将该元表附加到您要返回的 lines

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

编辑:要回答 OP 的评论,这样的电话:

lines:readArgs(1)

只是语法糖:

lines.readArgs(lines, 1)

当 lua VM 执行上述行时,会发生以下情况:

  • lines 是否有readArgs 键?
  • 如果是,则将其对应的值照常用于语句的其余部分。
  • 如果没有,lines 是否有 metatable.__index?在这种情况下确实如此,因此使用分配给 __index.readArgs 的函数。
  • readArgs 现在使用上述参数调用:self = lines, linenum = 1

这里self没有什么特别之处,只是一个常规参数;你可以给它起任何你想要的名字。

【讨论】:

  • 这里使用的self参数代表什么?被调用的表?我用我的语法测试了你提供的代码,它工作得很好,但我希望能够更好地理解这段代码
  • 我已经添加了一些解释。看看有没有帮助。
  • 所以澄清一下,因为 Lua 找不到 lines["readArgs"],它在元表中寻找 __index["readArgs"]?
  • 正确,如果你在一个不存在的表中查询一个键,lua 将查询元表作为后备。如果没有与该表关联的元表,那么您只需照常获得nil
猜你喜欢
  • 1970-01-01
  • 2019-12-30
  • 2021-12-28
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-11-03
  • 2013-05-08
  • 1970-01-01
相关资源
最近更新 更多