-1

I am trying to make a table, name given by the first arg of a function and assign a value to a key named by the second arg. For example

function myinsert(a, b)
    a.b = 10

For example when I give args pencil and price, pencil table to be created and pencil.price to be 10. Or other args, lesson and grade, making lesson.grade = 10. But as I try this it gives that it can't index local a (number value). What should I do? Thanks a lot

hjpotter92
  • 78,589
  • 36
  • 144
  • 183
  • 1
    Add your entire code, including the part where you call the function. – Yu Hao Sep 23 '14 at 07:28
  • Values, including tables, do no have names; variables do. Do you mean that `a` refers to a table or that `a` refers to a string that names a variable that refers to a table? – Tom Blodget Sep 23 '14 at 16:54
  • Also note that your `b` parameter is not being used. Try an IDE that helps you understand what your code is doing. – Tom Blodget Sep 23 '14 at 16:55

2 Answers2

0

You can use the loadstring function, which will evaluate arbitrary code in string

http://www.lua.org/pil/14.1.html

Example:

function myinsert(a, b)
  f = loadstring(string.format("%s={}; %s.%s=10", a, a, b))
  f()
lisu
  • 2,213
  • 14
  • 22
0

You can use _G[a]={[b]=10} to create a global table whose name is stored in a. The name of field to receive 10 is stored in b.

For example:

a = "pencil"
b = "price"
_G[a]={[b]=10}

is the same as

pencil.price=10

The code works even if a or b are not really names, that is, they don't have to be strings.

lhf
  • 70,581
  • 9
  • 108
  • 149