2
votes

I use Sol2 in my project and I have some trouble running C++ functions from Lua. First of all, I binded some functions to lua via sol::set_function(). For example:

I have this function:

void PrintInt(int value){
    std::cout << "Something" << std::endl;
}

In my main I do this:

int main() {
    sol::state state;
    state.set_function("PrintInt", &PrintInt);
}

Now if I call function in Lua it works fine. But I have some situations in my game code which can produce some unexpected calls, like this one in Lua:

PrintInt(nil)

All code here is pseudocode, so doesn't matter how this happen. It can be, because Lua scripts are written by gamer. So question is how can I avoid this to happen? I don't want to force player write checks and etc.

I have checks in C++ at load and running script, but it doesn't provide me any error. I use sol::protected_function_result to check for errors. I tried to use sol::optional, but I got "Cannot find class '', to resolve delegate 'optional'".

1
Then write check yourself... what's the problem? - user202729
Don't tag in title. - user202729
What is SoI2? Can you give some background? If that's a Lua interop library, then I'd start by reading its documentation, which will surely specify the behaviour you're asking about. - Kerrek SB
Repost. - nwp
OMG, it works! @KerrekSB, thank you very much! I don't know how, but last time I read docs, I skiped article about safety in running Lua code! Thank you again! - Darell_Ldark

1 Answers

1
votes

Well, thanks to comments and holy Sol2 docs!

Solution so easy and obvious: you just need to read this: Sol2 Docs: config and safety. After that just define any trigger you need like this: #define SOL_SAFE_USERTYPE 1. Your define should be in first place. After it you can include sol.hpp:

#define SOL_SAFE_USERTYPE 1
#include "sol.hpp"

That's all you should do.