Inject global variables into Skulpt before running code.

188 views
Skip to first unread message

Creston Bunch

unread,
Oct 26, 2015, 1:09:44 PM10/26/15
to Skulpt
Hi all,

What I would like to do is insert some global variables into the scope using Javascript before I even execute some Python code.

i.e., if I define a constant somewhere unbeknownst to the user
INJECTED_CONSTANT = 'Hello World';

then the user only has to write the code:
print INJECTED_CONSTANT

to print
'Hello World'

What would be the best way to do this?

Note: I don't want to just concatenate new lines before the user's code, as that will mess up line numbers in errors and the user needs to be able to see the correct line numbers.

Thanks.

Michael Cimino

unread,
Oct 27, 2015, 10:01:32 AM10/27/15
to Skulpt
This may not be the "correct" answer, but it's what I find works:

Since Sk.globals seems to gets re-initialized when the program is run, the best place I've found to store this kind of information is in Sk.builtins
For example, to make the below work, try this:
Sk.builtins.INJECTED_CONSTANT = 'Hello, World!';
or even better yet:
Sk.builtins.INJECTED_CONSTANT = Sk.builtin.str('Hello, World!');

Creston Bunch

unread,
Oct 28, 2015, 6:19:10 PM10/28/15
to Skulpt
That was also the best solution I could come up with.

I'm wondering if in the future Skulpt could have hooks for different events. For example, when it finds a new variable,I could load my own predefined values if it is undefined. (This would be nice because currently I'm adding about ~4000 variables to Sk.builtins and it's slowing down the run time I think).

I haven't taken the opportunity to look into Skulpt's source too deeply yet, but there is already a Sk.onAfterImport hook, so would it make sense to add hooks for different sorts of events? I don't know. Maybe there's a better place to discuss that.

Anyways, thanks for the help Michael! Cheers.
Reply all
Reply to author
Forward
0 new messages