ceifa / wasmoon

A real lua 5.4 VM with JS bindings made with webassembly
MIT License
480 stars 31 forks source link

Read and Write operations directly in browser memory #115

Closed Srikanth-Mohankumar closed 4 months ago

Srikanth-Mohankumar commented 4 months ago

I’m working on a project that involves running Lua scripts in a web browser using WebAssembly. Specifically, I need to perform file read and write operations directly in browser memory for an XML to TeX conversion tool. However, I’ve encountered issues with “require wasmoon” and Browserify installation errors.

Could you provide guidance on resolving these challenges?

run-lua.js:

const { LuaFactory } = require('wasmoon')

async function runLuaScript() {
    const factory = new LuaFactory()
    const lua = await factory.createEngine()

    try {
        await lua.doFile('dom-streamer.lua')
    } finally {
        lua.global.close()
    }
}

runLuaScript()

index.html:

<!DOCTYPE html>
<html>
<head>
    <title>Run Lua Script</title>
</head>
<body>
    <input type="file" id="fileInput">
    <button onclick="runLuaScript()">Run Lua Script</button>
    <pre id="output"></pre>

    <script src="run-lua.js"></script>
    <script>
        function runLuaScript() {
            const fileInput = document.getElementById('fileInput')
            const file = fileInput.files[0]
            if (!file) {
                alert('Please choose a file.')
                return
            }

            const reader = new FileReader()
            reader.onload = function(e) {
                const text = e.target.result
                // TODO: Pass the text to the Lua script and run it
                const output = '...' // TODO: Get the output from the Lua script
                document.getElementById('output').textContent = output
            }
            reader.readAsText(file)
        }
    </script>
</body>
</html>

dom-streamer.lua:

local inputFileName = arg[1]
local file = io.open(inputFileName, "r")
local xml = file:read("*all")
file:close()
local text = xml:gsub("<[^>]+>", "")
local preamble = "\\documentclass{article}\n\\begin{document}\n"
local postamble = "\\end{document}"
local outputFileName = "output.tex"
local file = io.open(outputFileName, "w")
file:write(preamble .. text .. postamble)
file:close()

input.xml:


<?xml version="1.0" encoding="UTF-8"?><title>Lua Programming</title><author>Srikanth</author><year>2024</year><message><text>Hello, World!</text></message>```
ceifa commented 4 months ago

Browserify is not needed for wasmoon, it works on browsers out of the box. Example: https://github.com/ceifa/lua-repl

Srikanth-Mohankumar commented 4 months ago

Thanks! I'll check.