Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Lua - local required eveytime a local variable is assigned?

Tags:

lua

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?

like image 427
Virus721 Avatar asked Mar 02 '16 09:03

Virus721


1 Answers

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
like image 121
hjpotter92 Avatar answered Oct 20 '22 02:10

hjpotter92