YetAnotherForum
Welcome Guest Search | Active Topics | Log In | Register

dofile sharing variables
comarius
#1 Posted : Friday, March 2, 2018 11:40:41 PM(UTC)
Rank: Newbie

Groups: Registered
Joined: 10/10/2017(UTC)
Posts: 5
Location: Toronto

Thanks: 0 times
Was thanked: 0 time(s) in 0 post(s)
Is there possible to share global variables between files.

file1.sc

Code:

local xxx = 7;

dofile("file2.sc");



file2.sc;

Code:
print(xxx + "\n");


absence
#2 Posted : Wednesday, March 21, 2018 5:04:49 PM(UTC)
Rank: Advanced Member

Groups: Registered
Joined: 8/23/2014(UTC)
Posts: 128
Man
Location: Northern Germany & Lincolnshire, U.K.

Thanks: 2 times
Was thanked: 10 time(s) in 10 post(s)
I think you probably understand dofile as some kind of "include" (which does not exist in Squirrel by default),
but dofile somewhat equals:

Code:
function() { /*content of file here* } () ;


In simple words, dofile is calling a function it compiles from a file.
a local (!) variable defined beforehand is not visible to it, as it enters a new stackframe.

The way you may imagine what (usually, depending on the host application) happens is:
this=getroottable() ;
function() { //function - on stack, creating a new stackframe, representing file1
local xxx=7 ; //object on stack (functions stackframe)
function() { print(xxx+"\n"); } (); //function on stack of first function, representing file2, again having its own stackframe, and call
} (); //call of first function (file 1)
[/code]
Hence, the local variable xxx of function 1 (file1) is _neighboring_ the function and stackframe of file 2 and is hence inaccessible - it is LOCAL to the function file1 produced.



you should do for example

Code:
xxx <- 7 ;

dofile("file2")


instead. xxx then is attached to the "this" object the executed file inherits from the scope of the current file (file1).
Note: As the this-object (usually) is a table a slot needs to be created, hence the <- operator instead of =


absence
#3 Posted : Wednesday, March 21, 2018 5:58:21 PM(UTC)
Rank: Advanced Member

Groups: Registered
Joined: 8/23/2014(UTC)
Posts: 128
Man
Location: Northern Germany & Lincolnshire, U.K.

Thanks: 2 times
Was thanked: 10 time(s) in 10 post(s)
addendum: just in case, xxx cannot be a "free variable" here (see docs), as dofile is a call and if you take it more exact than I put above, there is no real function declaration following the local xxx=... (instead it's rather a double function call happening, isolating things from any local variable on the stack)



Users browsing this topic
Guest (3)
Forum Jump  
You cannot post new topics in this forum.
You cannot reply to topics in this forum.
You cannot delete your posts in this forum.
You cannot edit your posts in this forum.
You cannot create polls in this forum.
You cannot vote in polls in this forum.

Clean Slate theme by Jaben Cargman (Tiny Gecko)
Powered by YAF 1.9.4 | YAF © 2003-2010, Yet Another Forum.NET
This page was generated in 0.074 seconds.