对于像 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
根据您的描述,听起来您正在寻找类似于此语法的内容:
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
Edit:要回答OP的评论,请拨打这样的电话:
lines:readArgs(1)
只是语法糖:
lines.readArgs(lines, 1)
当 lua VM 执行上述行时,会发生以下情况:
- 表有吗
lines
have a readArgs
key?
- 如果是,则像往常一样将其相应的值用于语句的其余部分。
- 如果没有,是否
lines
有元表.__索引吗?在这种情况下确实如此,因此函数分配给__index.readArgs
用来。
-
readArgs
现在使用上面的参数调用:self
= 线,linenum
= 1
没什么特别的self
这里,它只是一个常规参数;您可以将其命名为您真正想要的任何名称。
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)