[Scilab-users] How to replicate what "load" does (aka creating variable in the current workspace from inside a function)?

Antoine Monmayrant amonmayr at laas.fr
Mon Feb 22 11:21:55 CET 2016


Hi all,

I need to create variables dynamically depending on what I parse from a text file.
For testing, I just made a simple script that parses the file and generates a string array that defines some variables:
    txt=["a=1";"b=2"];
I then 
    execstr(txt);;
to create the variables needed (here "a" and "b").
So far, so good.
Now, I need to refactor my code to turn my messy script into a proper set of functions (see example code below).
The issue now is that I can't figure out how to define "a" and "b" from within the function.
I tried to declare them as "global" inside the function, but it does not work: as I haven't  declared them global at the top level before calling my function, it cannot work.
Sadly, as I don't know in advance the variables I'll find when I parse the file, I cannot declare the variables global at the top level.

Any solution or workaround?

Cheers,

Antoine

/////example code

//script version:

clear a b;
exists("a")// nope
exists("b")// nope
txt=["a=1";"b=2"];//typical result from parsing my txt file
execstr(txt);
exists("a")// yes
exists("b")// yes

//now with a function

//broken & useless 
function myload()
    txt=["a=1";"b=2"];
    //string to declare a and b global
    globaltxt="global "+strsubst(txt, '/=.*/', ';','r');
    //does not work
    execstr(globaltxt);
    execstr(txt);
endfunction


//does not work
clear a b;
exists("a")// nope
exists("b")// nope
myload()//
exists("a")// nope
exists("b")// nope


//this will work
clear a b
exists("a")// nope
exists("b")// nope
global a b // well I can't do that in practice, I don't know a and b in advance
myload()//
exists("a")// nope
exists("b")// nope






More information about the users mailing list