简体   繁体   中英

How to split string values in lua. Error

So I'm trying to split just a string I've read in through a csv file. The string contains several values such as first_name, last_name, email_address, etc... I want to use the split function to assign all those values to my own specific variables. So far this is what I have:

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

I'm getting an error in lua saying "Attempt to call global 'split' (a nil value)

I've googled with no success on the error message. Do I possibly have to include a library to use the split function????

Or am I just using the split function wrong. Any help is greatly appreciated :/

I don't believe that Lua has a split function as you're trying to use it. This page seems to be a thorough summary of how to split (and join) strings in Lua.

you may try this python-like split implementation I wrote.

Arguments:

  • s -- the string you want to be splitted

  • pattern -- it's the delimiter (a char or a string)

  • maxsplit -- at most this splits will be perfomed

Returns a table containing the splits.

Examples:

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

I hope it helps -^.^- Bye

You can get the split function from the pl.stringx package:

Install the penlight package:

luarocks install penlight

Then in the program, you can use the package as shown here:

local split = require("pl.stringx").split
local paths = split("/a/b/feature-name/d", "/") 
-- output: {,a,b,feature-name,d}
local feature = paths[4] 
-- output: feature-name

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM