如何在lua

时间:2015-10-15 09:26:27

标签: lua

我正在尝试打开一个文件并搜索特定的字符串并将我的内容与该特定字符串相关联以备将来使用,并再次保存该文件。

到目前为止,我设法打开一个文件并将内容写入文件。但我正在寻找逻辑来搜索文件的内容并查找特定字符串并将我的数据与该字符串相关联。它更像是一个查找表供将来参考。到目前为止,我的代码看起来像这样

--write something to a file
function wrt2file(arg1)
  file=io.open("/test.txt","a+")
  file:write(arg1)
  file:close()
end

--to search for a string and associate a new string to it
function search(arg1,arg2,arg3)
--i m looking for a function which will search for the string(arg1) in the file(arg2) and stick arg3 that location so that it can be used as a look uptable.

end
wrt2file("hello")
local content="hello"
search(content,"hi.txt","world")

怎么做?

1 个答案:

答案 0 :(得分:1)

你应该看看pattern-matching functions in Lua

我不清楚你是否要替换文件中的字符串,或者记住文件中字符串的位置。

要替换,您可以使用gsub函数,其工作方式如下:

-- the string you are searching in:
str = 'an example string with the word hello in it'

-- search for the word 'hello' and replace it with 'hello world',
-- and return a new string
new_str = str:gsub('hello', 'hello world')

-- new_str is 'an example string with the word hello world in it'

如果您只是想记住文件中可以找到字符串的位置,您应该使用find,其工作方式如下:

-- the string you are searching in:
str = 'an example string with the word hello in it'

-- search for the position of the word 'hello' in str
offset = str:find('hello')

-- offset now contains the number 33, which is the position
-- of the word 'hello' in str
-- save this position somewhere:
wrt2file(('world %d'):format(offset))
-- your '/test.txt' file now contains 'world 33'