• There is NO official Otland's Discord server and NO official Otland's server list. The Otland's Staff does not manage any Discord server or server list. Moderators or administrator of any Discord server or server lists have NO connection to the Otland's Staff. Do not get scammed!

Lua How to convert a string into a variable name?

Xikini

I whore myself out for likes
Senator
Premium User
Joined
Nov 17, 2010
Messages
6,784
Solutions
581
Reaction score
5,349
I've been wracking my brain trying to figure this out.. xD

So in the source we basically have this..
Lua:
CONST_ME_NONE = 0
CONST_ME_DRAWBLOOD = 1
CONST_ME_LOSEENERGY = 2

in the script I have this..
Lua:
local effects = {CONST_ME_NONE, CONST_ME_DRAWBLOOD, CONST_ME_LOSEENERGY}

local user_input = "CONST_ME_NONE"

for i = 1, #effects do
    if effects[i] == user_input then
        -- do something
    end
end

How do I convert user_input into the variable name, so that I can then use it to compare against what's in the table without needing to explicitly write out a look-up table?
 
Solution
load("return " .. user_input)()

Lua:
local user_input = "CONST_ME_DRAWBLOOD"
position:sendMagicEffect(load("return " .. user_input)())

#Edit
loadstring is obsolete in 5.1+ Lua version, changing to load.

#Edit2
This is not secure, if this is used in TalkAction, then player can simply execute Lua code with this script.
load("return " .. user_input)()

Lua:
local user_input = "CONST_ME_DRAWBLOOD"
position:sendMagicEffect(load("return " .. user_input)())

#Edit
loadstring is obsolete in 5.1+ Lua version, changing to load.

#Edit2
This is not secure, if this is used in TalkAction, then player can simply execute Lua code with this script.
 
Last edited:
Solution
This is not secure, if this is used in TalkAction, then player can simply execute Lua code with this script.
Oh hmm.
Yeah I was planning on using this in a talkaction, and possibly npc scenario's.
Using the loadstring is useful, since I can use numbers or the variable name and get the same result.

Can you think of any alternative other then writing out the look-up table for this specific use-case?

Lua:
local effects = {
    ["CONST_ME_NONE"] = CONST_ME_NONE,
    ["CONST_ME_DRAWBLOOD"] = CONST_ME_DRAWBLOOD,
    ["CONST_ME_LOSEENERGY"] = CONST_ME_LOSEENERGY
}
 
Try _G[user_input]
I swear I tried this earlier and couldn't get it to work. lmao

Thank you.
Post automatically merged:

Try _G[user_input]
Sorry to ping you, but it's basically the same thing in reverse.. xD
How do I print the variable name instead of the value?
lmao it seems so simple, but googling for 2 hours has literally got me no-where.

Lua:
local effects = {CONST_ME_NONE, CONST_ME_DRAWBLOOD, CONST_ME_LOSEENERGY}

print(effects[1]) -- this prints '0'.. how do I make it print "CONST_ME_NONE"
 
Last edited:
Back
Top