This is a read-only snapshot of the ComputerCraft forums, taken in April 2020.
Evert's profile picture

Weird result in string split function

Started by Evert, 17 August 2012 - 03:32 PM
Evert #1
Posted 17 August 2012 - 05:32 PM
Hello everyone!
I made a string split function (based on a function from lua-users.org) that seems to give a very strange result.
Here is the code:


local function strsplit(regex, string, times)
local tab = {}
local startt = 1
local positie, eindpos = string.find(string, regex, startt)

if not times then
   times = 0
end

local i = 1
while times == 0 or (positie and i <= times)  do
  if not positie then
	break
  end
  table.insert(tab, string.sub(string, startt, positie-1))
  startt = eindpos + 1
  positie, eindpos = string.find(string, regex, startt)
  i = i+1
end

table.insert(tab, string.sub(string, startt, -1))
return(tab)
end

local test = "apple 1\npear 2\nbanana 3"
local table = {}
table = strsplit("\n",test,3)
table[1] = strsplit(" ",table[1],1)
table[2] = strsplit(" ",table[2],1)
table[3] = strsplit(" ",table[3],1)
print(table[1][1] .. "---" .. table[1][2])
print("---")
print(table[2][1] .. "---" .. table[2][2])
print("---")
print(table[3][1] .. "---" .. table[3][2])
print("---")

In minecraft (tekkit) this gives the output:


apple---1
---
pear 2---
---
banana 3---
---
So I thought, there must be something wrong with the function.

But since I'm a Linux user, I can easily run this on my own computer, but it throws a different (but correct!) result.


$ lua strsplit
apple---1
---
pear---2
---
banana---3
---

I don't know where the fault lies, so maybe you can help me.

Details:
Tekkit 1.2.5 (SMP)
Linux lua version: 5.1.5-2
Cloudy #2
Posted 17 August 2012 - 09:26 PM
Known issue with string.find in LuaJ. We will probably be moving away from LuaJ soon, but weirdly, this workaround works:

string.find(string.."", regex, startt)
Evert #3
Posted 18 August 2012 - 10:21 AM
Known issue with string.find in LuaJ. We will probably be moving away from LuaJ soon, but weirdly, this workaround works:
string.find(string.."", regex, startt)
Thanks very much. Works like a charm.
smickles #4
Posted 02 March 2013 - 04:20 PM
Known issue with string.find in LuaJ. We will probably be moving away from LuaJ soon, but weirdly, this workaround works:

string.find(string.."", regex, startt)
Searched all over for a solution for my problem in all the "lua" places. nothing. then found computercraft used luaj and looked there, still nothing. Somehow, I found this post. Thank you :D/>
remiX #5
Posted 02 March 2013 - 07:17 PM
Isn't the fact that he's using the string api and a variable named string also messing something up?
ChunLing #6
Posted 02 March 2013 - 11:51 PM
Probably. Anyway, the core problem is mentioned in the wiki under string API. The wiki makes an effort to mention where a core Lua API does not function as expected, so it's worth checking in these cases.