table.insert and string.gsub

Posted by Mahony on Tue 23 Sep 2014 12:46 PM — 6 posts, 22,013 views.

#0
I'm trying to insert a string that I need to adjust before entering.


%1 is amulet aardwolf                            |

t = {}
table.insert(t, "string.gsub("%1","( +)|","")")

I get error
[string "Trigger: "]:2: ')' expected near 'amulet'


I read lue table details and help for lua tables and searched forum...

When I do it this way

%1 is amulet aardwolf                            |
aaa = string.gsub("%1","( +)|","")
t = {}
table.insert(t, "aaa")


it works. But I don't want to use another variable and I think it must work the first way... somehow
USA Global Moderator #1
Quote:
But I don't want to use another variable

That is a bad reason.


Anyway, in your first attempt you should change
table.insert(t, "string.gsub("%1","( +)|","")")

to
table.insert(t, string.gsub("%1","( +)|",""))




Also, your second attempt doesn't actually work.
You want
table.insert(t, aaa)

not
table.insert(t, "aaa")
Amended on Tue 23 Sep 2014 01:23 PM by Fiendish
#2
here is what i get if I omit the quotes

table.insert(t, string.gsub("%1","( +)|",""))

Run-time error
World: Aardwolf
Immediate execution
[string "Trigger: "]:6: bad argument #2 to 'insert' (number expected, got string)
stack traceback:
        [C]: in function 'insert'
        [string "Trigger: "]:6: in main chunk


I played with all sorts of quotes and didn't get the result.. :(
You are right with the second part

table.insert(t, aaa)

is correct and works.
Amended on Tue 23 Sep 2014 01:45 PM by Mahony
USA Global Moderator #3
Mahony said:

here is what i get if I omit the quotes

table.insert(t, string.gsub("%1","( +)|",""))

Run-time error
World: Aardwolf
Immediate execution
[string "Trigger: "]:6: bad argument #2 to 'insert' (number expected, got string)
stack traceback:
        [C]: in function 'insert'
        [string "Trigger: "]:6: in main chunk



Ah...of course. Sorry, I wasn't thinking. gsub returns multiple values. So you can't directly pass it to table.insert. What the second one is doing is implicitly dropping the second return value from gsub.
Australia Forum Administrator #4
What's your regexp doing? You can't use the "|" in Lua regexps (unless you are looking for "|"). In PCRE regexeps the "|" symbol means "or".


foo = "amulet          aardwolf"

t = {}
table.insert(t, (string.gsub(foo," +"," ")))

require "tprint"
tprint (t)


That example removes the spaces in foo. The brackets around string.gsub forces the return of the first result only.

[EDIT] Ah I see now. Try this:


foo = "amulet aardwolf                            |"

t = {}
table.insert(t, (string.gsub(foo," +|","")))

tprint (t)


Replace foo by "%1" and it should work, eg.


t = {}
table.insert(t, (string.gsub("%1"," +|","")))
Amended on Tue 23 Sep 2014 08:36 PM by Nick Gammon
#5
It works! :) Thank you Nick