如何在lua中分割字符串值。错误

所以我正在尝试仅拆分通过csv文件读入的字符串。 字符串包含许多值,例如 first_namelast_nameemail_address 等等... 我想使用拆分函数将所有这些值分配给我自己的特定变量。 到目前为止,这就是我所拥有的:

first_name,last_name,email_address,street_address,city,state = split(line,",")
person_record = {first_name,last_name,email_address,street_address,city,state}

我在lua中遇到了一个错误,即“尝试调用全局 'split'(空值)”。

我搜索了谷歌,但没有成功解决错误消息。 我可能必须包括库才能使用split函数吗????

还是我只是错误使用split函数。 非常感谢任何帮助:/

原文链接 https://stackoverflow.com/questions/9961178

点赞
stackoverflow用户147356
stackoverflow用户147356

我不认为Lua有一个像你尝试使用的split函数。这个页面似乎是关于如何在Lua中分割(和连接)字符串的全面摘要。

2012-04-01 01:30:05
stackoverflow用户1539602
stackoverflow用户1539602

将下面翻译成中文并且保留原本的 markdown 格式

如果你想要一个类 Python 的分割函数,你可以尝试我写的这个。

参数:

  • s -- 要分割的字符串

  • pattern -- 分隔符(一个字符或者字符串)

  • maxsplit -- 最多分割多少次

返回一个包含分割结果的表格。

示例:

split('potato', 't') --> {'po', 'a', 'o'}

split('potato', 't', 1) --> {'po', 'ato'}

split('potato', 'ta') --> {'po', 'to'}

split('potato', 'foo') --> {'potato'}

split = function(s, pattern, maxsplit)
  local pattern = pattern or ' '
  local maxsplit = maxsplit or -1
  local s = s
  local t = {}
  local patsz = #pattern
  while maxsplit ~= 0 do
    local curpos = 1
    local found = string.find(s, pattern)
    if found ~= nil then
      table.insert(t, string.sub(s, curpos, found - 1))
      curpos = found + patsz
      s = string.sub(s, curpos)
    else
      table.insert(t, string.sub(s, curpos))
      break
    end
    maxsplit = maxsplit - 1
    if maxsplit == 0 then
      table.insert(t, string.sub(s, curpos - patsz - 1))
    end
  end
  return t
end

希望它有所帮助 -^。^- 再见

2012-08-03 02:55:47
stackoverflow用户10502646
stackoverflow用户10502646

你可以从 pl.stringx 包中获取 split 函数:

安装 penlight 包:

luarocks install penlight

然后在程序中,你可以像下面这样使用这个包:

local split = require("pl.stringx").split
local paths = split("/a/b/feature-name/d", "/")
-- 输出:{,a,b,feature-name,d}
local feature = paths[4]
-- 输出:feature-name
2020-11-02 00:54:12