Skip to content

Commit

Permalink
init.lua: change method for print() from coroutines
Browse files Browse the repository at this point in the history
  • Loading branch information
Ildar Mulyukov committed Jun 30, 2020
1 parent cf71adf commit 7f477c4
Show file tree
Hide file tree
Showing 3 changed files with 42 additions and 129 deletions.
32 changes: 32 additions & 0 deletions app/src/main/assets/call_in_mainthread.lua
Original file line number Diff line number Diff line change
@@ -0,0 +1,32 @@
-- Helper module for changing call context from a coroutine to the main thread

local mainthread_stash = {}

local function mainthread_call(f, ...)
local thread = coroutine.running()
assert(thread, "cannot call from the main thread")
mainthread_stash[thread] = mainthread_stash[thread] or {}
mainthread_stash[thread].status = nil
mainthread_stash[thread].f = f
mainthread_stash[thread].args = {...}
while mainthread_stash[thread].status == nil do
coroutine.yield()
end
return mainthread_stash[thread].status, mainthread_stash[thread].res
end

local function mainthread_process()
local co, main = coroutine.running()
assert( main or co == nil, "cannot call from a coroutine")
for thread,_ in pairs(mainthread_stash) do
if mainthread_stash[thread].status == nil then
mainthread_stash[thread].status, mainthread_stash[thread].res =
pcall( mainthread_stash[thread].f, unpack(mainthread_stash[thread].args) )
end
end
end

return {
mainthread_call = mainthread_call,
mainthread_process = mainthread_process,
}
114 changes: 0 additions & 114 deletions app/src/main/assets/fifo.lua

This file was deleted.

25 changes: 10 additions & 15 deletions app/src/main/assets/init.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,27 +3,22 @@

-- replace print
local Log = luajava.bindClass 'android.util.Log'
local print_spooler_fifo = require("fifo") () ; print_spooler_fifo:setempty(function() return nil; end)
function print_spooler()
assert( not coroutine.running(), "print_spooler() cannot be used from a coroutine" )
local msg_tab = print_spooler_fifo:pop()
while msg_tab do
Log:v("lua-print", table.concat(msg_tab,'\t'))
msg_tab = print_spooler_fifo:pop()
end
end
local cim = require 'call_in_mainthread'
function print(...)
local args = {...}
if tostring(args[1]):find("No such method") then
print_spooler_fifo:push( { debug.traceback() } )
end
for i=1,#args do
args[i] = tostring(args[i])
end
print_spooler_fifo:push( args )
if not coroutine.running() then
print_spooler()
if coroutine.running() then
cim.mainthread_call(Log.v, Log, "lua-print-co", table.concat(args,'\t'))
else
cim.mainthread_process()
Log:v("lua-print", table.concat(args,'\t'))
end
--[[ if tostring(args[1]):find("No such method") then
print( { debug.traceback() } )
end
]]
end

print "AndroidLuaSDK init finished"

0 comments on commit 7f477c4

Please sign in to comment.