How to make a function's argument part of a string?

Posted by Eloni on Sun 25 Dec 2016 02:11 AM — 4 posts, 17,407 views.

#0
I feel like this is a dumb question, but it has been bothering me for a few days. None of these work. I feel like I'm misunderstanding something very basic. I couldn't get this to work with a simple print function, either.



Code:

function killThis2(thing)

		DoAfterSpecial(math.random(1,3), "Send('kill ', (thing))", 12)
  
end 


Sends to mud:


kill nil

------
Code:

something = ""

function killThis3(thing)


something = thing

		DoAfterSpecial(math.random(1,3), "Send('kill ' .. (thing))", 12)
  
end 


Returns error:


Run-time error
World: world.org
Immediate execution
[string "Timer: "]:1: attempt to concatenate global 'thing' (a nil value)
stack traceback:
        [string "Timer: "]:1: in main chunk		

----
Code:

function killThis4(thing)

		DoAfterSpecial(math.random(1,3), "Send('kill ', [[thing]])", 12)
  
end 


Sends to mud:

kill thing
Amended on Sun 25 Dec 2016 02:14 AM by Eloni
USA Global Moderator #1

function say_something_in_three_seconds (thing)
   DoAfterSpecial(3, "Send('say "..thing.."')", 12)
end
Amended on Sun 25 Dec 2016 09:25 AM by Fiendish
#2
Thank you very much! This is exactly what I was looking for.
Australia Forum Administrator #3
I've been thinking about why this doesn't work:


function killThis2(thing)
  DoAfterSpecial(math.random(1,3), "Send('kill ', (thing))", sendto.script)
end 


The reason is the scope of the variable thing.

That variable exists only inside the function 'killThis2' - it is a parameter, and thus only has meaning while that function executes. However what `DoAfterSpecial` does is create a timer for the specified interval that sends:


Send('kill ', (thing))


The brackets aren't necessary. Anyway, the problem is, that in 3 seconds time thing won't exist in the context in which the timer is executed. Hence it will be nil.

Fiendish's suggest of concatenating the argument like this fixes it:


DoAfterSpecial(3, "Send('say "..thing.."')", sendto.script)


Now what gets queued up is:


Send('say hello Nick')



This is because thing is being evaluated right now, inside the function (assuming thing is "hello Nick") and thus the correct word is queued for the timer.