How to access table key using a function parameter?

local t = {a=1, b=2, c=3} local function check (key)     print( t.key  ) end print (t.a) ---\> 1 check(a) ---\> nil

Why doesn’t the function work?!

Hi Abdo23,
You can refer the following:

[lua]

local t = {a=1, b=2, c=3}

for key,value in pairs(t) do

  print("key   = ", key)

  print("value = ", value)

end

[/lua]

_ While in your case:

  • You are passing ‘a’ as parameter to check function. ‘a’ is nothing but nil.
  • ‘a’ is not declare nor initialize anywhere, thus it is showing nil,
  • To refer the properties of a table like ‘keys’ & ‘value’, you have to use reference of that table.
       like in your case you have used : table.key -> to print the value _
     

Kindly
Assif  :) 
 

@Abdo23

You’ve got that slightly wrong.

Try this:

local t = {a=1, b=2, c=3} local function check (key) print( t[key] ) end print (t.a) ---\> 1 check("a") ---\> 1 check("b") ---\> 2

That works perfectly. Thanks 

Good solution roaminggamer,

I missed it as question was not clear.

Keep it up. :) 

 

Hi Abdo23,
You can refer the following:

[lua]

local t = {a=1, b=2, c=3}

for key,value in pairs(t) do

  print("key   = ", key)

  print("value = ", value)

end

[/lua]

_ While in your case:

  • You are passing ‘a’ as parameter to check function. ‘a’ is nothing but nil.
  • ‘a’ is not declare nor initialize anywhere, thus it is showing nil,
  • To refer the properties of a table like ‘keys’ & ‘value’, you have to use reference of that table.
       like in your case you have used : table.key -> to print the value _
     

Kindly
Assif  :) 
 

@Abdo23

You’ve got that slightly wrong.

Try this:

local t = {a=1, b=2, c=3} local function check (key) print( t[key] ) end print (t.a) ---\> 1 check("a") ---\> 1 check("b") ---\> 2

That works perfectly. Thanks 

Good solution roaminggamer,

I missed it as question was not clear.

Keep it up. :)