2019-05-22 07:17:31 +08:00
|
|
|
#define SOL_ALL_SAFETIES_ON 1
|
2018-09-28 13:27:38 +08:00
|
|
|
#include <sol/sol.hpp>
|
2018-03-16 05:16:28 +08:00
|
|
|
|
|
|
|
#include <iostream>
|
|
|
|
|
|
|
|
struct object {
|
2021-03-06 14:03:23 +08:00
|
|
|
void my_func() {
|
|
|
|
std::cout << "hello\n";
|
|
|
|
}
|
2018-03-16 05:16:28 +08:00
|
|
|
};
|
|
|
|
|
|
|
|
int deny(lua_State* L) {
|
2021-03-06 14:03:23 +08:00
|
|
|
return luaL_error(L, "HAH! Deniiiiied!");
|
2018-03-16 05:16:28 +08:00
|
|
|
}
|
|
|
|
|
2019-05-22 07:17:31 +08:00
|
|
|
int main(int, char*[]) {
|
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
sol::state lua;
|
|
|
|
lua.open_libraries(sol::lib::base);
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
object my_obj;
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
sol::table obj_table = lua.create_named_table("object");
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
sol::table obj_metatable = lua.create_table_with();
|
2021-03-06 23:14:48 +08:00
|
|
|
obj_metatable.set_function(
|
|
|
|
"my_func", &object::my_func, &my_obj);
|
2021-03-06 14:03:23 +08:00
|
|
|
// Set whatever else you need to
|
|
|
|
// on the obj_metatable,
|
|
|
|
// not on the obj_table itself!
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
// Properly self-index metatable to block things
|
|
|
|
obj_metatable[sol::meta_function::new_index] = deny;
|
|
|
|
obj_metatable[sol::meta_function::index] = obj_metatable;
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
// Set it on the actual table
|
|
|
|
obj_table[sol::metatable_key] = obj_metatable;
|
2018-03-16 05:16:28 +08:00
|
|
|
|
2021-03-06 14:03:23 +08:00
|
|
|
try {
|
|
|
|
lua.script(R"(
|
2018-03-16 05:16:28 +08:00
|
|
|
print(object.my_func)
|
|
|
|
object["my_func"] = 24
|
|
|
|
print(object.my_func)
|
|
|
|
)");
|
2021-03-06 14:03:23 +08:00
|
|
|
}
|
|
|
|
catch (const std::exception& e) {
|
2021-03-06 23:14:48 +08:00
|
|
|
std::cout << "an expected error occurred: " << e.what()
|
|
|
|
<< std::endl;
|
2021-03-06 14:03:23 +08:00
|
|
|
}
|
|
|
|
return 0;
|
2018-03-16 05:16:28 +08:00
|
|
|
}
|