2

--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 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you, I appreciate your response understand your point, But it's just the requirement in my case, so could you please let me know a way to do that?
Why is that the requirement in your case? As I said, Lua doesn't support dynamic scoping and I really doubt that that is going to be the best solution to your problem. Could you edit your question to add some more context?
Actually, I am not allowed to change the parameters that are being passed to the function
I find it strange that you can't change the parameters but can change the function body. What is going on? I really do think you need to give a more complete example explaining why you even have these unusual restrictions.
I can't change the parameters of the function because the function I am calling from within the forloop, the name of the function is not hard coded and several similar functions are called from that skeleton,for one function,I can not change that skeleton that is being used to call many other functions
|
4
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.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.