The following function does the job:

function myload()
  txt=["a=1";"b=2"];
  ncur= size(who("local"),"*")
  execstr(txt);
  vars=who("local");
  vars=vars(1:size(vars,'*')-ncur-1)
  args=strcat(vars,",")
  execstr("["+args+"]=resume("+args+")")
endfunction

Serge
Le 22/02/2016 11:21, Antoine Monmayrant a écrit :
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



_______________________________________________
users mailing list
users@lists.scilab.org
http://lists.scilab.org/mailman/listinfo/users


_______________________________________________
users mailing list
users@lists.scilab.org
http://lists.scilab.org/mailman/listinfo/users

Reply via email to