2
votes

--main.lua

for o = 1, 5 do
  print(o)
  SampleFunction()
end

--in B.lua

function SampleFunction()
  print(o)   --prints nil
end

I have a for loop, which is iterating over a range. Inside that for loop, I am calling a function which is in some other Lua file and I need the iterator variable to be accessible in the other Lua file, but it just prints NIL every time, what do I need to do?

2

2 Answers

5
votes

Having a function use variables from its caller can be very brittle so its not something that Lua supports. What would happen if you called SampleFuncction from another place that doesn't have an o variable?

The way I would do this is to have have SampleFunction receive the loop index as a parameter

-- main.lua

for o = 1, 5 do
  print(o)
  SampleFunction(o)
end

--in B.lua

function SampleFunction(index)
    print(index)
end
3
votes
for i = 1, 5 do
    o = i
    SampleFunction()
end

The for-loop iterator is always locally-scoped to loop body, but you may assign it's value to any available global variable. Note that this is still not dynamic scoping -- you overwrite global o and this may interfere with other functions using that name.