Skip to content

Instantly share code, notes, and snippets.

@ChaunceyHoover
Last active August 8, 2019 12:56
Show Gist options
  • Save ChaunceyHoover/5b43c83f0bd9be4908d90f30cb1652f8 to your computer and use it in GitHub Desktop.
Save ChaunceyHoover/5b43c83f0bd9be4908d90f30cb1652f8 to your computer and use it in GitHub Desktop.
Simple separator/explode function for Lua
function explode(input, separator)
if input:len() == 0 then return {} end
if input:len() == 1 then return { input } end
separator = type(separator) == "string" and separator:sub(1, 1) or tostring(separator)
local results = {}
local lastPos = 1 -- Note: in Lua, '1' is the start of everything, including strings
for i = 1, input:len() do -- or: for i = 1, string.len(input) do
if string.sub(input, i, i) == separator then -- or: if input:sub(i, i) == separator then
table.insert(results, string.sub(input, lastPos, i - 1))
lastPos = i + 1 -- Not set to 'i' because that would be the comma itself
end
end
if string.len(input) ~= lastPos then
table.insert(results, string.sub(input, lastPos)) -- This is to get the very last argument
end
return results
end
for i, v in pairs( explode("hello,world,how,are,you") ) do
print(v)
end
@ChaunceyHoover
Copy link
Author

Just importing old pastebin scripts to my gist

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment