Help regarding scope?

All development conversation and discussion takes place here

Moderator: Moderator

Post Reply
Message
Author
nate
Wyrmic
Posts: 261
Joined: Fri Jan 18, 2013 8:35 am

Help regarding scope?

#1 Post by nate »

The next stumbling block for me writing Lua well is scope. I seem to be stumbling around it. I get the right answer eventually, but I don't have a good understanding of why-- it's just trial and error. Since there are some good people around here, I thought I might ask for help. Really, I want an abstract understanding of how Lua handles it. Tutorials haven't been much use, because they don't deal with any complicated situations.

To start the ball rolling, let's look at dofile. Imagine I have a file named File, and in that file I have the following:

Code: Select all

t= {}
t.first = true
someothervalue = 1
So if I

Code: Select all

someothervalue = 2
dofile(File)
print(someothervalue)
I get 1 as my output. But if I

Code: Select all

t={}
dofile(File)
if t.first then print("1") else print("2") end
then I get 2.

What's going on with that? Why can't I retrieve table keys and values via dofile? (I want to be able to write files with various keys, and not have to create every possible key I could generate before reading my file.) This seems like a scope issue, because I can't even get any values without declaring the variable first in my code (I'll just get nil), and if I declare my variable as local, then the dofile won't write to it at all, even though it seems like the dofile is part of the same scope.
Proud father of Fx4fx and Chronometer add-ons; proud mother of Fated add-on

aardvark
Wyrmic
Posts: 200
Joined: Wed Aug 22, 2012 12:16 am

Re: Help regarding scope?

#2 Post by aardvark »

nate wrote:But if I

Code: Select all

t={}
dofile(File)
if t.first then print("1") else print("2") end
then I get 2.

What's going on with that?
What's wrong with that is that there's something wrong with your Lua interpreter. t is a global variable and should be modified correctly by File's contents.

As for populating a table from another file, what you're probably searching for is a combination of loadfile() and setfenv() (in Lua 5.1, which is used in the T-Engine 4), or just loadfile() (in Lua 5.2, which you may be using standalone). There's a pretty good explanation on Stack Overflow, though it's got extra error check functions thrown in to complicate the example. A step-by-step, every line does one thing, no error checking included translation would look something like

Code: Select all

-- load and run a script in the provided environment
-- returns the modified environment table
function run(scriptfile)
	local env = {}
	setmetatable(env, {__index=_G})
	local f = loadfile(scriptfile)
	setfenv(f, env)
	f()
	setmetatable(env, nil)
	return env
end
By setting the environment of f() (which is a function that executes the contents of File) to env, any of f()'s changes to global variables modify only the contents of env. That is, as far as f() is concerned, it's modifying global variables even though it's only changing the contents of env.

Lua 5.2 is different in that the setfenv() function no longer exists. You just pass the environment table (if any) directly to loadfile().

nate
Wyrmic
Posts: 261
Joined: Fri Jan 18, 2013 8:35 am

Re: Help regarding scope?

#3 Post by nate »

Well, what was wrong with it was a collection of small syntax errors that weren't breaking things on their own, I was interpreting what was going on incorrectly, and because my code was too unwieldy to put into concise form on a message board, I revised it into a simpler form, one where those errors were no longer appearing. The apparent interaction with modularity and dofile prevented me from double checking my paraphrase on the online Lua console I use.

Where I keep running into problems is trying to get scope to penetrate, and keeping track of my references to self, but my knowledge isn't yet at the point where I can even phrase my problems correctly. (For instance, after a bit of experimentation, I found loadfile and dofile working differently in how they handled scope, but I don't understand why. Or rather I think they did, but once I got my code working, I stopped looking at their differences.) I guess I've just got to face up to the fact that it takes more than three weeks to learn how to code well, and I'm just making too many errors and not noticing them for too long. Periods that should be colons are frequent offenders; recently, it took an awfully long time away from the computer to see that a "for in pairs(t)" lacked the "pairs".

I'm embarassed of asking for help when the answer comes to me eventually, and especially when I don't phrase things in such a way that anybody could ever help, but I also feel like it's just part of how I solve problems-- the problems are getting complicated enough that trying to describe them in English is part of the solution. I guess I'm saying don't judge me too harshly for long, useless, difficult-to-understand posts like this :)

I appreciate the link: it would certainly be a good idea for me to worry about limiting scope more than I do. (It's occurred to me that by using dofile(), I'm probably making a mod where somebody who wants to can get a highly cheated character onto the vault, but frankly, I'm more worried about just accessing my variables from various scopes.)

setfenv sounds like something I need to read about. I'll look around a bit. It's probably a little out of my depth still, but reading stuff before I understand it seems like the way to get to a point where I can eventually understand it. Looking at metatable tutorials, they've seemed like "other ways to do things that make your code prettier," when I'm not even good enough at the basics to worry about that, but it does seem that it's time to start dipping my toes into it.

Thanks for looking. Sorry that I made you look at lies. (edit: hey, cool, i just managed to control my reference to "self" in a useful way on the first try, guess I'm getting somewhere)
Proud father of Fx4fx and Chronometer add-ons; proud mother of Fated add-on

Canderel
Sher'Tul
Posts: 1252
Joined: Mon Nov 24, 2003 2:31 pm
Location: South Africa

Re: Help regarding scope?

#4 Post by Canderel »

For me I often find my answer by trying to ask the question.

So while I am trying to explain or simplify what I dont understand, I often come to understand it.

Post Reply