Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Round-trip C# byte[] as Lua string #508

Open
s5bug opened this issue Dec 1, 2023 · 2 comments
Open

Round-trip C# byte[] as Lua string #508

s5bug opened this issue Dec 1, 2023 · 2 comments

Comments

@s5bug
Copy link

s5bug commented Dec 1, 2023

I'm working with a Lua script that requires binary data be written/read in string form (the io functions are operating on binary files). I cannot change this as I'm required to be backwards compatible with existing scripts. How do I register a function on the NLua context such that a byte[] is returned as a Lua string and not a System.Byte[]?

public byte[] ReadString(long /*nint*/ address, int length, bool absolute = false) {
01:00:07.931 ERR | NLua.Exceptions.LuaScriptException: ...Autosave.lua:59: bad argument #1 to 'write' (string expected, got System.Byte[], System.Private.CoreLib, Version=7.0.0.0, Culture=neutral, PublicKeyToken=7cec85d7bea7798e)

This data is not valid UTF-8 and as such will not survive a raw → UTF16 → UTF8 roundtrip.

@viniciusjarina
Copy link
Member

Can you write a test case?. I can't understand the error with this amount of information.
Maybe you need to use string.char and convert the byte array to Lua string
https://github.com/NLua/NLua/blob/main/tests/src/LuaTests.cs#L2956

@s5bug
Copy link
Author

s5bug commented Dec 2, 2023

I cannot modify the extant Lua scripts, so using string.char is not an option for me.

Here's the script I'm working with:

if ReadInt(continue+0xC) ~= prevContinue and ReadByte(0x711438-offset2) == 0 and blacklisted == false then
    local f = io.open("KH2autosave.dat", "wb")
    f:write(ReadString(continue, 0x10FC0))
    f:close()
    ConsolePrint("Wrote autosave")
end

I am expected to implement ReadString. It must be able to:

  • Read binary data from address 0x10FC0 from a byte buffer (not valid UTF-8 data, which is why using string will not work)
  • Report that binary data to the Lua side as a Lua string for use with f:write

I can't write a test case for this unless the behavior of returning a byte[] from Lua#RegisterFunction should be changed to be Translated as a Lua string.

Here's the other side of the code, which can actually accept a byte[] due to the Translator supporting Lua string → C# byte[]:

local f = io.open("KH2autosave.dat", "rb")
if f ~= nil then
    WriteString(save1, f:read("*a"))
    f:close()
    ConsolePrint("Loaded autosave")
end

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants