Srdjan M.
Srdjan M.

Reputation: 3405

Passing value as a parameter in Lua

A = {}

function A:text()
    return 100
end

print(A["text"]()) -- prints "100"

----------------------------------

A = {}

function A:text(value)
    return value
end

print(A["text"](100)) -- prints "nil"

Is there a way that I can pass a value as a parameter and return the same value?I need to loop through 5 functions...

Upvotes: 0

Views: 1764

Answers (2)

Srdjan M.
Srdjan M.

Reputation: 3405

As "Nicol Bolas" pointed out, I add table/self parameter and it worked fine.

-- from "A["text"](100)" to "A["text"](self, 100)" or "A["text"](A, 100)"

A = {}
B = {"text", "type"}

function A:text(value)
    return "text "..value
end

function A:type(value)
    return "type "..value
end

for i=1, 3 do
   for j=1, #B do
      print(A[B[j]](self, i)) -- prints "text 1 type 1 text 2 type 2 text 3 type 3"
   end
end

Upvotes: 1

Nicol Bolas
Nicol Bolas

Reputation: 474386

You could, if you declared your function correctly.

function A:text(value)

This creates a function that takes two parameters. The : is what's responsible for that. The first parameter is an implicitly declared parameter called self. The second is value. This function is intended to be called as A:text(100) or with A["text"](A, 100).

These are for class-member-like functions.

You should instead create the function like this:

function A.text(value)

This creates a function that takes one parameter.

Upvotes: 5

Related Questions