I'm trying to reproduce in Lua the mIRC scripting manipulating tokens function:
local function tokenize(C, text) local char = string.format("%c", C) local t = {} for w in string.gmatch(tostring(text), "[^"..char.."]+") do w = tonumber(w) or tostring(w) table.insert(t,w) end return t end local function gettok(strng, position, separator, range) local char = string.format("%c", separator) local tokens = tokenize(separator, strng) local result, n, r, start, stop if (position ~= 0) then if (position > 0) then n = position else n = #tokens + position + 1 end if (range) and (position ~= range) then if (range > 0) then r = range elseif (range == 0) or ((n + range) > #tokens) then r = #tokens else r = n + (range + 1) end if (n == r) then result = tokens[i] else start = (r >= n) and n or r stop = (r <= n) and n or r for i = start, stop do result = (not result) and tokens[i] or tostring(result..char..tokens[i]) end end else for i = 1, #tokens do if (i == n) then result = tokens[i] end end end else result = strng end return result end
And this is the way it should work:
gettok(strng, position, separator, range)
Where
strng
= string to manipulateposition
= position of the token inside the string. If lesser than 0, it will be considered the position from the last token to the first. If equal to 0, returns the whole string.separator
= ASCII code of the token separatorrange
= optional: if specified, returns the token from position to range. If equal to 0, return all tokens from position to the end of the string.
local text = "apple.banana.cherry.grape.orange"
apple
gettok(text,1,46)
grape
gettok(text,-2,46)
banana.cherry.grape
gettok(text,2,46,4)
cherry.grape.orange
gettok(text,-1,46,-3)
Could you give me some advice on improving the code?