feat: add normalizeLuaStructure and normalizeLuaComponent functions for Lua data handling

This commit is contained in:
2025-12-29 22:49:22 +00:00
parent 3f5f9d66cc
commit 3f12f2d23a
2 changed files with 58 additions and 2 deletions

View File

@@ -4,6 +4,7 @@ import * as fengari from 'fengari-web'
import { createLuaEngine } from '@/lib/lua/engine/core/create-lua-engine'
import { pushToLua } from '@/lib/lua/functions/converters/push-to-lua'
import { fromLua } from '@/lib/lua/functions/converters/from-lua'
import { normalizeLuaComponent } from './normalize-lua-structure'
import type { LuaUIManifest, LuaUIPackage, LuaUIPage, LuaUIComponent } from './types/lua-ui-package'
const lua = fengari.lua
@@ -67,8 +68,9 @@ export async function loadLuaUIPackage(packagePath: string): Promise<LuaUIPackag
throw new Error(`Error calling render() in ${pageManifest.file}: ${errorMsg}`)
}
// Convert the result to JavaScript
const layout = fromLua(L, -1) as LuaUIComponent
// Convert the result to JavaScript and normalize arrays
const rawLayout = fromLua(L, -1)
const layout = normalizeLuaComponent(rawLayout)
lua.lua_pop(L, 2) // Pop result and module table
engine.destroy()

View File

@@ -0,0 +1,54 @@
import type { LuaUIComponent } from './types/lua-ui-package'
/**
* Normalize a Lua-converted structure to ensure arrays are properly converted
* Lua tables with sequential numeric keys (1, 2, 3...) should be JavaScript arrays
*/
export function normalizeLuaStructure(value: any): any {
if (value === null || value === undefined) {
return value
}
if (Array.isArray(value)) {
return value.map(normalizeLuaStructure)
}
if (typeof value === 'object') {
const keys = Object.keys(value)
// Check if this looks like a Lua array (all keys are sequential numbers starting from 1)
const isLuaArray = keys.every((key) => {
const num = Number(key)
return Number.isInteger(num) && num >= 1
})
if (isLuaArray && keys.length > 0) {
// Convert to JavaScript array
const arr: any[] = []
const sortedKeys = keys.map(Number).sort((a, b) => a - b)
for (const key of sortedKeys) {
arr.push(normalizeLuaStructure(value[key]))
}
return arr
}
// Otherwise, recursively normalize the object
const normalized: any = {}
for (const key of keys) {
normalized[key] = normalizeLuaStructure(value[key])
}
return normalized
}
return value
}
/**
* Normalize a LuaUIComponent structure
*/
export function normalizeLuaComponent(component: any): LuaUIComponent {
return normalizeLuaStructure(component) as LuaUIComponent
}