Variables scope and functions called from C++


#1

I know that when you write a lambda you have to capture the outside variables to make them available inside the lambda. But what about functions? Do functions have access only to GLOBAL variables? I have doubts regarding this because of how the following code works.

C++

struct Test
{
    void print()
    {
        std::cout << "Printed" << std::endl;
    }
};

// ...

engine.add(user_type<Test>(), "Test");
engine.add(constructor<Test()>(), "Test");
engine.add(fun(&Test::print), "print");
engine.eval_file("script.chai");

Script

var t := Test();
t.print();

def func()
{
    t.print();
}

func(); // this raises an error "Can not find object t"

Everything is fine so far (at least works as expected), but when I try to call func from C++, it works without errors:

auto func = engine.eval<std::function<void()>>("func");
func();

Is it a bug or intended behavior?


#2

It looks like you’ve uncovered a bug - function variable scope is not properly being set up when calling a ChaiScript function from C++.

Can you create a bug report https://github.com/ChaiScript/ChaiScript/issues

I’ll be able to fix that next week.

-Jason


#3

Sure, done https://github.com/ChaiScript/ChaiScript/issues/191