Request for coding native plugins guide

Hi Vlads,

Firstly following on from Rob’s comment above - I’ve reposted the question here https://forums.coronalabs.com/topic/70218-plugin-implementation-in-corona-native/

Also - that was the one thing that occurred to me - however I *thought* that the block acted like a lua closure and that the state would still be valid, I was also under the impression that the block ran on the same thread, but in hindsight I can see the problem.

I’ll try your fix and also check out the link above (as well as doing some background reading on the dispatch functionality as well.

Thanks for your help.

:slight_smile:

UPDATE : I did the fix above as suggested and got the same issue - whilst I understand that the code inside the block (basically the sendFrequency() function) is running on the same thread it’s obvious (and I should have realised) that since some time has now passed and the reference to the lua_State is the same the actual state itself is likely to have changed.

What I don’t understand is what this code does

PluginLibrary \*PluginLibrary::ToLibrary( lua\_State \*L ) { // library is pushed as part of the closure Self \*library = (Self \*)CoronaLuaToUserdata( L, lua\_upvalueindex( 1 ) ); return library; }

Because when XCode throws an error L appears to have a valid value, as does library but when you expand library the fListener reference is 0x0 (and probably the cause of a null pointer exception)

Ahhh - I think now it’s starting to make sense.

int PluginLibrary::Open( lua\_State \*L ) { // Snip... // Set library as upvalue for each library function Self \*library = new Self; CoronaLuaPushUserdata( L, library, kMetatableName ); luaL\_openlib( L, kName, kVTable, 1 ); // leave "library" on top of stack return 1; }

My understanding is that the above creates an instance of the plugin library and then pushes the reference as userdata which is then picked up and returned in the ToLibrary() method - this initially threw me as all the rest of the methods are declared as static.

Block do act as Lua closure, and everything is still valid in it. Otherwise you wouldn’t be able to access L in it at all. Point here that while Lua is single threaded, Objective C (and Java) isn’t. So you “have to wait” for your turn to access it on “main thread”. This is exactly what dispatch_async(dispatch_get_main_queue(), ^{…}) does. It creates a block on main thread, which would wait for it’s turn to be executed when everything else is done.

Ok - thanks for the update.

I have been able to get it work (in a fashion), what I did was store a local copy of the fListener variable rather than using the value in the userdata and it didn’t crash. 

Obviously this isn’t a viable long term solution and I’d like to understand why I can’t access the correct reference from the userdata but it doesn’t crash (which is a start :wink: )