Virus721
Virus721

Reputation: 8315

Lua - local required eveytime a local variable is assigned?

I've found a strange piece of code in the Lua documentation :

function trim8(s)
  local i1,i2 = find(s,'^%s*')
  if i2 >= i1 then s = sub(s,i2+1) end
  local i1,i2 = find(s,'%s*$')
  if i2 >= i1 then s = sub(s,1,i1-1) end
  return s
end

Why is local used once again with i1 and i2? Aren't they already declared among local variables? Do you have to repeat the local keyword every time you want to assign them?

Upvotes: 9

Views: 1262

Answers (2)

hjpotter92
hjpotter92

Reputation: 80629

No, it is not necessary to use local over and over. The variables i1 and i2 will be local in the scope of the function because of the first line itself.

While it should not be done, there is nothing wrong with defining the same variables over and over. It will just assign a new position in stack to the newer, and shadow the older one.

The following is the instruction output for a simple function:

function t()
    local i = 2
    local i = 3
end
t()
function <temp.lua:1,4> (3 instructions, 12 bytes at 00658990)
0 params, 2 slots, 0 upvalues, 2 locals, 2 constants, 0 functions
        1       [2]     LOADK           0 -1    ; 2
        2       [3]     LOADK           1 -2    ; 3
        3       [4]     RETURN          0 1

and updating the second local i = 3 to just i = 3:

function t()
    local i = 2
    i = 3
end
t()
function <temp.lua:1,4> (3 instructions, 12 bytes at 00478990)
0 params, 2 slots, 0 upvalues, 1 local, 2 constants, 0 functions
        1       [2]     LOADK           0 -1    ; 2
        2       [3]     LOADK           0 -2    ; 3
        3       [4]     RETURN          0 1

Notice the difference at the second instruction.


Apart from that, the function is quite inefficient. You can instead use the following:

function Trim(sInput)
    return sInput:match "^%s*(.-)%s*$"
end

Upvotes: 8

Yu Hao
Yu Hao

Reputation: 122373

Technically, using local or not in the second declaration are not equivalent. Using a second local would declare another variable.

However in your example code, they have basically the same. Check these simpler code:

local a = 0
local a = 1

and

local a = 0
a = 1

Use luac -p -l outputs the following result:

0+ params, 2 slots, 0 upvalues, 2 locals, 2 constants, 0 functions
    1   [1] LOADK       0 -1    ; 0
    2   [2] LOADK       1 -2    ; 1
    3   [2] RETURN      0 1

and

0+ params, 2 slots, 0 upvalues, 1 local, 2 constants, 0 functions
    1   [1] LOADK       0 -1    ; 0
    2   [2] LOADK       0 -2    ; 1
    3   [2] RETURN      0 1

Upvotes: 5

Related Questions