Discord
Login
Community
DARK THEME

creating a new variable from a string combination

in my programm i got multiple variables which are pretty similar, and to safe some time i was wondering if i could convert a string back to a variable, its hard to explain but an example would be;

map_1=[1,2,3]

map_2=[4,5,6]

mapnumber=function(lv) // lv is 1 or 2

 local b = "map_"+lv

 print b[1]

end

i hope you can understand what i wanna do, i really dont know how to explain it better

mapList = []
mapList.push([1,2,3])
mapList.push([4,5,6])

currentMap = mapList[ mapNumber ]

print( curentMap )

thanks! didnt know u could add lists into lists, this helps a lot!

MicroScript has a table where it holds references to all global variables. There are two ways to refer to a variable in MicroScript

  • by a dot
  • through square brackets

So something like this will work.

   a = 123
   print( global.a )
   print( global[ 'a' ])
   str = 'a'
   print( global[ str ])
   print( global.str )
   
   map_1 = [ 1,2,3 ]
   map_2 = [ 4,5,6 ]
   
   str = 'map_'
   count = '2'
   print( str + count )
   print( global[ str + count ])

Within a class, you can also refer to variables like this with "this" .

MyClass = class
  constructor = function()
    this.abc_1 = "string abc_1"
    this.abc_2 = "string abc_2"
  end
  getVar = function( name )
    return this[ name ]
  end
end

   myClass = new MyClass()
   count = "2"
   print( myClass.getVar( "abc_1"))
   print( myClass.getVar( "abc_"+count ))

Post a reply

Progress

Status

Preview
Cancel
Post
Validate your e-mail address to participate in the community