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

[solved] string API returning function

Started by viluon, 06 May 2014 - 05:38 PM
viluon #1
Posted 06 May 2014 - 07:38 PM
Solved thanks to Lignum! And thanks also to CometWolf for his time :D/>

out="asd"
test=string.gmatch(out,"+"," ")
print(type(test))
Prints "function". It's not a bug in the print(), the variable test behaves like a function in other cases too. Please correct me if I am doing something wrong.

Note: if out contains "+", the output is the same. Tested on CC 1.63 pure Minecraft+Forge. Tested on standalone code also (no custom environment, overrides or whatever)
Edited on 06 May 2014 - 06:04 PM
Lignum #2
Posted 06 May 2014 - 07:54 PM
Not a bug. string.gmatch returns a function which acts as an iterator.
Change line 2 to:

test = string.gmatch(out, "%+", " ")()
And you will get correct results.
Also, in this case the "+" should be prefixed with "%" since "+" is a special character in Lua Patterns.
viluon #3
Posted 06 May 2014 - 07:58 PM
Not a bug. string.gmatch returns a function which acts as an iterator.
Change line 2 to:

test = string.gmatch(out, "%+", " ")()
And you will get correct results.
Also, in this case the "+" should be prefixed with "%" since "+" is a special character in Lua Patterns.
Oh thanks I got the % there in the original code, I didn't know about the iteration… thanks anyway :)/> I got the function I used this code in from outside CC (a bit different Lua) and forgot to check compatibility as string is a default API.
CometWolf #4
Posted 06 May 2014 - 07:59 PM
I suggest you read up on the function you are attempting to use, prior to using it.
http://lua-users.org/wiki/StringLibraryTutorial
gmatch is an iterator function, similar to pairs. That means the first return value is a function to be used in a for loop, the second is the actual result of that specific call.

for word in string.gmatch("Hey you","%S") do
  print(word)
end

Note to self: i always get ninjaed when on the phone!
Edited on 06 May 2014 - 06:00 PM
Lyqyd #5
Posted 06 May 2014 - 09:04 PM
You might have been looking for string.gsub, based on the parameters you were using.