@@ -5,7 +5,7 @@ use bevy::{
5
5
ecs:: { entity:: Entity , world:: World } ,
6
6
} ;
7
7
use bevy_mod_scripting_core:: {
8
- asset:: { AssetPathToLanguageMapper , Language } ,
8
+ asset:: { AssetPathToLanguageMapper , Language , ScriptEnvironmentStore } ,
9
9
bindings:: {
10
10
function:: namespace:: Namespace , globals:: AppScriptGlobalsRegistry ,
11
11
script_value:: ScriptValue , ThreadWorldContainer , WorldContainer ,
@@ -172,11 +172,25 @@ fn load_lua_content_into_context(
172
172
. iter ( )
173
173
. try_for_each ( |init| init ( script_id, Entity :: from_raw ( 0 ) , context) ) ?;
174
174
175
+ // isolate the script's globals into an environment
176
+ let metatable = context. create_table ( ) ?;
177
+ metatable. set ( "__index" , context. globals ( ) ) ?;
178
+ let env = context. create_table ( ) ?;
179
+ env. set_metatable ( Some ( metatable) ) ;
180
+
175
181
context
176
182
. load ( content)
183
+ . set_environment ( env. clone ( ) )
177
184
. exec ( )
178
185
. map_err ( ScriptError :: from_mlua_error) ?;
179
186
187
+ // store the env in the store so we can call BMS event handlers from them
188
+ let world = ThreadWorldContainer . try_get_world ( ) ?;
189
+ world. with_global_access ( move |w| {
190
+ let map = & mut w. resource_mut :: < ScriptEnvironmentStore > ( ) . map ;
191
+ map. insert ( script_id. clone ( ) , env. clone ( ) ) ;
192
+ } ) ?;
193
+
180
194
Ok ( ( ) )
181
195
}
182
196
@@ -240,7 +254,18 @@ pub fn lua_handler(
240
254
. iter ( )
241
255
. try_for_each ( |init| init ( script_id, entity, context) ) ?;
242
256
243
- let handler: Function = match context. globals ( ) . raw_get ( callback_label. as_ref ( ) ) {
257
+ // we need the world to access the ScriptEnvironmentStore
258
+ // we will find the environment that belongs to this script to call the function
259
+ let world = ThreadWorldContainer . try_get_world ( ) ?;
260
+ let env = world. with_global_access ( |w| {
261
+ w. resource :: < ScriptEnvironmentStore > ( )
262
+ . map
263
+ . get ( script_id)
264
+ . unwrap ( )
265
+ . clone ( )
266
+ } ) ?;
267
+
268
+ let handler: Function = match env. raw_get ( callback_label. as_ref ( ) ) {
244
269
Ok ( handler) => handler,
245
270
// not subscribed to this event type
246
271
Err ( _) => {
0 commit comments