@@ -3,7 +3,7 @@ use std::os::raw::{c_int, c_void};
33use std:: { ptr, str} ;
44
55use crate :: error:: Result ;
6- use crate :: util:: { check_stack, get_metatable_ptr, push_string , push_table , rawset_field, TypeKey } ;
6+ use crate :: util:: { check_stack, get_metatable_ptr, push_table , rawget_field , rawset_field, TypeKey } ;
77
88// Pushes the userdata and attaches a metatable with __gc method.
99// Internally uses 3 stack spaces, does not call checkstack.
@@ -154,14 +154,11 @@ pub(crate) unsafe fn init_userdata_metatable(
154154 methods : Option < c_int > ,
155155 extra_init : Option < fn ( * mut ffi:: lua_State ) -> Result < ( ) > > ,
156156) -> Result < ( ) > {
157- ffi:: lua_pushvalue ( state, metatable) ;
158-
159157 if field_getters. is_some ( ) || methods. is_some ( ) {
160158 // Push `__index` generator function
161159 init_userdata_metatable_index ( state) ?;
162160
163- push_string ( state, b"__index" , true ) ?;
164- let index_type = ffi:: lua_rawget ( state, -3 ) ;
161+ let index_type = rawget_field ( state, metatable, "__index" ) ?;
165162 match index_type {
166163 ffi:: LUA_TNIL | ffi:: LUA_TTABLE | ffi:: LUA_TFUNCTION => {
167164 for & idx in & [ field_getters, methods] {
@@ -175,28 +172,27 @@ pub(crate) unsafe fn init_userdata_metatable(
175172 // Generate `__index`
176173 protect_lua ! ( state, 4 , 1 , fn ( state) ffi:: lua_call( state, 3 , 1 ) ) ?;
177174 }
178- _ => mlua_panic ! ( "improper __index type {}" , index_type) ,
175+ _ => mlua_panic ! ( "improper ` __index` type: {}" , index_type) ,
179176 }
180177
181- rawset_field ( state, - 2 , "__index" ) ?;
178+ rawset_field ( state, metatable , "__index" ) ?;
182179 }
183180
184181 if let Some ( field_setters) = field_setters {
185182 // Push `__newindex` generator function
186183 init_userdata_metatable_newindex ( state) ?;
187184
188- push_string ( state, b"__newindex" , true ) ?;
189- let newindex_type = ffi:: lua_rawget ( state, -3 ) ;
185+ let newindex_type = rawget_field ( state, metatable, "__newindex" ) ?;
190186 match newindex_type {
191187 ffi:: LUA_TNIL | ffi:: LUA_TTABLE | ffi:: LUA_TFUNCTION => {
192188 ffi:: lua_pushvalue ( state, field_setters) ;
193189 // Generate `__newindex`
194190 protect_lua ! ( state, 3 , 1 , fn ( state) ffi:: lua_call( state, 2 , 1 ) ) ?;
195191 }
196- _ => mlua_panic ! ( "improper __newindex type {}" , newindex_type) ,
192+ _ => mlua_panic ! ( "improper ` __newindex` type: {}" , newindex_type) ,
197193 }
198194
199- rawset_field ( state, - 2 , "__newindex" ) ?;
195+ rawset_field ( state, metatable , "__newindex" ) ?;
200196 }
201197
202198 // Additional initialization
@@ -205,9 +201,7 @@ pub(crate) unsafe fn init_userdata_metatable(
205201 }
206202
207203 ffi:: lua_pushboolean ( state, 0 ) ;
208- rawset_field ( state, -2 , "__metatable" ) ?;
209-
210- ffi:: lua_pop ( state, 1 ) ;
204+ rawset_field ( state, metatable, "__metatable" ) ?;
211205
212206 Ok ( ( ) )
213207}
0 commit comments