Jump to content

Change string to variable


undefined

Recommended Posts

pers = "pers" 

Oh, no!

e.g

--Client 
function testFunc() 
    triggerServerEvent("testTrigger", localPlayer, "pers") 
end 
  
--Server 
local testTable = { 
    pers = {"test1","test2"} 
} 
addEvent("testTrigger", true) 
addEventHandler("testTrigger", getRootElement(), function(test) 
outputChatBox("The table say: "..(testTable.test[#testTable.test])..".") -- I want to get testTable.pers but it's get testTable."pers" 
end 

How to change "pers" to pers... :roll::roll::roll:

Link to comment
If test is a string, try using testTable[test]

But i need remove the string.

Like Mr.Aleks said, use testTable[test]

That will give you the table which holds "test1" and "test2". testTable[test] is the same as testTable.pers if test is a string that is equal to "pers", just like testTable["pers"] is the same as testTable.pers

Link to comment
  • Moderators

tables can replace every variable in your whole code if you want.

  
myScript = { 
["variableName"] = "IIYAMA", 
["variableWhut"] = 345763645984366, 
["thisFunction"]= function () outputChatBox("thisFunction") end, 
["thatFunction"]= function () outputChatBox("thatFunction")  end  
}  
  
outputChatBox(myScript["variableName"]) 
  
outputChatBox(myScript["variableWhut"]) 
  
myScript["thisFunction"]() 
  
myScript["thatFunction"]() 

as arezu said you can also use the: .

outputChatBox(myScript.variableName) 
myScript.thisFunction() 
  

and this is how you clear them:

myScript["thisFunction"] = nil 
myScript.thisFunction = nil 

I prefer the ["name"], because in my opinion it is clearer and you will have the benefit that you can put every kind of data between the [ ]. Which can make your code more dynamic.

When you use the . you can only access with strings.

Link to comment
try it

loadstring ( "return paris" ) (   ) 

if you don't know about environments then it's better not to use loadstring because you can't nil the variable just like that, you need to change environment using

setmetatable 

and you don't even need to use loadstring for this + lua.org suggests that you should use pcall.

local var = loadstring ("print(1)") 
pcall (var) 
  

Link to comment

Create an account or sign in to comment

You need to be a member in order to leave a comment

Create an account

Sign up for a new account in our community. It's easy!

Register a new account

Sign in

Already have an account? Sign in here.

Sign In Now
  • Recently Browsing   0 members

    • No registered users viewing this page.
×
×
  • Create New...