I added lua to my project but now I don’t know how to add lua files!
Is there a way to add data files to my project? And if so, how does my program load the data at runtime?
I get that there is no file system.
I added lua to my project but now I don’t know how to add lua files!
Is there a way to add data files to my project? And if so, how does my program load the data at runtime?
I get that there is no file system.
You can create a simple code generation script and add it to your platformio.ini
:
extra_scripts = embed_resources.py
This is my script:
#!/usr/bin/env python3
from typing import Dict, List, Tuple
import datetime
import glob
root_dir = 'res/LuaScripts'
def get_files() -> List[str]:
files = glob.glob(f'{root_dir}/**/*.lua', recursive=True)
# Remove the root directory from the path
files = [file.replace(f'{root_dir}/', '') for file in files]
return list(files)
def read_files(files) -> Dict[str, str]:
content = {}
for file in files:
with open(f'{root_dir}/{file}', 'r') as lua_file:
content[file] = lua_file.read()
return content
def path_to_namespace(path: str) -> Tuple[str, str]:
""" Path.To.Script.lua -> Path::To::Script """
path_parts = path.split('/')
file_name = path_parts[-1].split('.')[0]
path_parts = path_parts[:-1]
path_parts.insert(0, 'Scripts')
namespace = '::'.join(path_parts)
return namespace, file_name
def write_header(file, found_files):
file.write(f"""
/* This file was generated at {datetime.datetime.now().strftime("%Y-%m-%d %H:%M:%S")}.
*
* DO NOT EDIT!
*
* Found {len(found_files)} lua files:
""")
for lua_file in found_files:
file.write(f' * {lua_file}\n')
file.write(' */\n\n')
files = read_files(get_files())
with open('src/Generated/LuaScripts.h', 'w') as file:
write_header(file, files)
file.write('#pragma once\n\n')
file.write('#include <string_view>\n\n')
file.write('namespace Lua {\n\n')
for lua_file, _ in files.items():
namespace, file_name = path_to_namespace(lua_file)
file.write(f'namespace {namespace} {{\n')
file.write(f' extern const std::string_view {file_name};\n')
file.write( '}\n')
file.write('\n} // namespace Lua\n')
with open('src/Generated/LuaScripts.cpp', 'w') as file:
write_header(file, files)
file.write('#include "./LuaScripts.h"\n')
file.write('#include "../LuaScripts.h"\n\n')
file.write('namespace Lua {\n\n')
file.write('const std::unordered_map<std::string_view, std::string_view> luaScripts = {')
for lua_file, content in files.items():
file.write(f'\n{{ "{lua_file}", ')
file.write(f'{path_to_namespace(lua_file)[0]}::{path_to_namespace(lua_file)[1]} }},')
file.write('};\n\n')
for lua_file, _ in files.items():
namespace, file_name = path_to_namespace(lua_file)
file.write(f'const constexpr std::string_view\n')
file.write(f'{namespace}::{file_name} {{\n')
file.write(f'R"LUA({files[lua_file]})LUA",\n')
file.write(f"{len(files[lua_file]):,}zu}};\n".replace(',', "'"))
file.write('\n} // namespace Lua\n\n')