kite
kite

Reputation: 313

Lua: problems when using parameters to reference table values

I'm missing something fundamental when it comes to parameters.

obj = {
    name = "hey"
}
function say_name(p,k)
    return p.k
end

print(say_name(obj,name))  --doesn't print "hey"

I don't understand why this isn't giving the same output as print(obj.name) i.e. "hey"
Changing the function yields the following cases:

function say_name(p) --works...makes sense to me
    return p.name
end
function say_name(p,k) --doesn't work...why does k not work the same as p?
    return p.k
end
function say_name(p,name) --works....why tho? isn't name a parameter like k is..?
    return p.name
end

Is it cause I'm referencing a table value with a parameter? Is there some rule to this I'm missing?

Upvotes: 2

Views: 291

Answers (1)

Piglet
Piglet

Reputation: 28994

Try this:

obj = {
    name = "hey"
}
function say_name(p,k)
    return p[k]
end

print(say_name(obj,"name"))

I added quotes around name. name is nil, but you need the string "name" to index obj.name or obj["name"] respectively

p.k is equivalent to p["k"] ! This only works for string keys that are valid Lua names. If you have a variable or any other key you need to use the square bracket notation.

From the Lua 5.4 Reference Manual - 3.2 Variables

Square brackets are used to index a table:

 var ::= prefixexp ‘[’ exp ‘]’

The meaning of accesses to table fields can be changed via metatables (see §2.4).

The syntax var.Name is just syntactic sugar for var["Name"]:

 var ::= prefixexp ‘.’ Name

function say_name(p,k) --doesn't work...why does k not work the same as p?
    return p.k
end

p.k is p["k"]. It has nothing to do with the parameter k of your function

function say_name(p,name) --works....why tho? isn't name a parameter like k is..?
    return p.name
end

p.name is p["name"]. It has nothing to do with your parameter name. It's just a conincidence that it works for obj.name because obj has a field "name", any other string wouldn't work

Upvotes: 3

Related Questions