daurnimator / lua.vm.js

The project is superceded by Fengari. See https://fengari.io/
MIT License
835 stars 101 forks source link

Avoid synchronous JavaScript operations? #25

Closed saucisson closed 8 years ago

saucisson commented 9 years ago

The load_lua_over_http function makes a synchronous call to XMLHttpRequest. As it is considered as a bad practice, an asynchronous call could be preferred.

This example shows how the usual imperative style of Lua can be used together with JavaScript's callbacks. This solution does not handle well errors. It also requires that the main Lua code is executed within a coroutine. This could be done automatically by L.execute, for instance.

Warning: using coroutines within coroutines in Lua can lead to wrong behavior (from the programmer's point of view). If a JavaScript asynchronous operation does a yield within a coroutine implemented iterator, the yield will be caught by the iterator instead of the main function. Philipp Janda and i have proposed a workaround in lua-coronest.

daurnimator commented 9 years ago

You need to use a synchronous XHR so that you can write normal looking lua code. It's considered bad practice in the Javascript world; but we're a little bit different :)

In an ideal word. we write some sort of preloader (which sets off many 'requires' at once and fills in package.preload). But I'd still have require as it is so that dynamic code works.

Alternatively, we could run all lua code inside of a coroutine; so that you can yield from the 'main' thread.