Optimize this code, improve the code, structure the code, improve the interface in this…
- User
Optimize this code, improve the code, structure the code, improve the interface in this lua code for teardown
lua - Assistant
Optimize this code, improve the code, structure the code, improve the interface in this lua code for teardown
function DrawDynamicTextButtons(condition, text1, text2, w, h, font, size, R, G, B)
local press = false
UiPush()
UiButtonPressDist(3)
UiFont(font, size)
UiButtonImageBox("ui/common/box-outline-6.png", 6, 6)
if condition then
UiColor(R, G, B)
UiButtonHoverColor(R*10, G*0.6, B*0.2)
if UiTextButton(text2, w, h) then
condition = not condition
press = true
end
else
UiColor(1, 1, 1)
UiButtonHoverColor(R*0.6, G, B*0.6)
if UiTextButton(text1, w, h) then
condition = not condition
press = true
end
end
UiPop()
return press, condition
end
-- need to copy and paste this because the #include keyword stopped working
function KeyInit()
setKey("savegame.mod.fire", true, true)
setKey("savegame.mod.dca", true, true)
setKey("savegame.mod.damage", true, true)
setKey("savegame.mod.machinegun", true, true)
setKey("savegame.mod.aircraft", true, true)
setKey("savegame.mod.mortar", true, true)
setKey("savegame.mod.music", true, true)
setKey("savegame.mod.lowconfig", false, true)
setKey("savegame.mod.start", false, true)
setKey("savegame.mod.start.key", 'c', false)
setKey("savegame.mod.flak", true, true)
end
function setKey(key, default, boolean, infinite)
boolean = boolean or false
infinite = infinite or false
if not HasKey(key) then
if boolean then
SetBool(key, default)
else
SetString(key, default)
end
end
if infinite then
if not HasKey(key .. "_infinite") then
SetBool(key .. "_infinite", false)
end
end
end
function init()
KeyInit()
end
function draw()
UiTranslate(UiCenter(), 0)
UiAlign("center middle")
--Draw buttons
UiTranslate(0, 0)
UiFont("regular.ttf", 26)
UiButtonImageBox("ui/common/box-outline-6.png", 6, 6)
local border = 80
UiTranslate(0, border)
DrawBoolButton("savegame.mod.fire", "Toggle this to randomnly spawn fire on start.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.dca", "Toggle this to have some DCA shots in the sky.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.damage", "Toggle this to randomnly destroy parts of the map on start (laggy during the first 30s of the simulation, as it progressively destroys the map).")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.lowconfig", "Toggle this if you have a small config and the previous feature make you crash or lag for too long.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.machinegun", "Toggle this to have machine gun sounds around you.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.aircraft", "Toggle this to make an aircraft pass sometimes in the sky.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.mortar", "Toggle this to add random mortar shots on the map.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.music", "Toggle this to activate the music.")
UiTranslate(0, border)
DrawBoolButton("savegame.mod.start", "Toggle this to activate the mod when you press any key you want instead of on-start. This allows you to freely set up your scene and also ending it.")
UiTranslate(0, border)
triggerkey = GetString("savegame.mod.start.key")
if triggerkey ~= "" then
keyDisplay = triggerkey
else
keyDisplay = "Not Assigned"
end
change, changeKey = DrawDynamicTextButtons(changeKey, keyDisplay, "Press A Key", 150, 35, "regular.ttf", 26, 1, 1, 1)
if changeKey and not autoEQ then
if InputLastPressedKey() == "tab" or InputLastPressedKey() == "esc" then
changeKey = false
else
if InputPressed(",") then
changeKey = false
SetString("savegame.mod.start.key", ",")
elseif InputPressed(".") then
changeKey = false
SetString("savegame.mod.start.key", ".")
elseif InputLastPressedKey() ~= "" then
changeKey = false
SetString("savegame.mod.start.key", InputLastPressedKey())
end
end
else
changeKey = false
end
UiTranslate(0, border)
DrawBoolButton("savegame.mod.flak", "Toggle this to activate the flak explosions in the sky.")
UiTranslate(0, 100)
if UiTextButton("Close", 200, 40) then
Menu()
end
end
local function bool_to_int(value)
return value == true and 1 or value == false and 0
end
local function int_to_bool(value)
return value > 0
end
function DrawIntSlider(key, lowerbound, upperbound, size, text, infinite)
infinite = infinite or false
UiPush()
UiAlign("center middle")
UiFont("regular.ttf", 22)
UiColor(0.9,0.9,0.025,1)
local value = GetInt(key)
if GetBool(key .. "_infinite") then
value = "Infinite"
end
UiText(text .. " " .. value, true)
UiColor(1,1,1,1)
UiFont("regular.ttf", 26)
UiImageBox("box-solid-6.png", (upperbound * size) - (lowerbound * (size * 0.5)), 20, 5, 5)
UiTranslate(-((upperbound * (size*0.5)) + (lowerbound * (size*0.5))), 0)
SetInt(key, UiSlider("dot_small.png", "x", GetInt(key) * size, lowerbound * size, upperbound * size) / size)
if infinite then
SetBool(key .. "_infinite", GetInt(key) == upperbound)
end
UiPop()
end
function DrawBoolButton(key, text)
UiPush()
UiAlign("center middle")
UiFont("regular.ttf", 22)
UiColor(0.9,0.9,0.025,1)
UiText(text, true)
UiTranslate(0, 15)
if GetBool(key) then
UiColor(0,1,0,1)
else
UiColor(1,0,0,1)
end
UiFont("regular.ttf", 26)
if UiTextButton("Toggled: " .. tostring(GetBool(key))) then
SetBool(key, not GetBool(key))
end
UiPop()
end
Certainly! Below is the optimized and refactored version of your Lua code for Teardown. The improvements focus on:
-- ==============================
-- Teardown Mod Configuration
-- ==============================
-- Initialize the mod settings with default values
local modSettings = {
{ key = "savegame.mod.fire", text = "Randomly spawn fire on start.", type = "bool" },
{ key = "savegame.mod.dca", text = "Have some DCA shots in the sky.", type = "bool" },
{ key = "savegame.mod.damage", text = "Randomly destroy parts of the map on start (laggy during the first 30s).", type = "bool" },
{ key = "savegame.mod.lowconfig", text = "Enable for small config to prevent crashes or long lags.", type = "bool" },
{ key = "savegame.mod.machinegun", text = "Enable machine gun sounds around you.", type = "bool" },
{ key = "savegame.mod.aircraft", text = "Make aircraft occasionally pass in the sky.", type = "bool" },
{ key = "savegame.mod.mortar", text = "Add random mortar shots on the map.", type = "bool" },
{ key = "savegame.mod.music", text = "Activate the music.", type = "bool" },
{
key = "savegame.mod.start",
text = "Activate the mod with a key press instead of on-start.",
type = "bool",
keyAssignment = {
key = "savegame.mod.start.key",
default = 'c',
description = "Key to toggle the mod"
}
},
{ key = "savegame.mod.flak", text = "Activate flak explosions in the sky.", type = "bool" },
}
-- ==============================
-- Helper Functions
-- ==============================
-- Sets a key with default value if it doesn't exist
local function setKey(key, default, isBool, infinite)
if not HasKey(key) then
if isBool then
SetBool(key, default)
else
SetString(key, default)
end
end
if infinite then
local infiniteKey = key .. "_infinite"
if not HasKey(infiniteKey) then
SetBool(infiniteKey, false)
end
end
end
-- Initialize all keys based on modSettings
local function initializeKeys()
for _, setting in ipairs(modSettings) do
if setting.type == "bool" then
setKey(setting.key, true, true)
elseif setting.type == "string" then
setKey(setting.key, "", false)
end
-- Initialize key assignments if present
if setting.keyAssignment then
setKey(setting.keyAssignment.key, setting.keyAssignment.default, false)
end
end
end
-- Converts boolean to integer (1 or 0)
local function boolToInt(value)
return value and 1 or 0
end
-- Converts integer to boolean (true or false)
local function intToBool(value)
return value > 0
end
-- ==============================
-- UI Rendering Functions
-- ==============================
-- Draws a dynamic text button that toggles between two states
local function drawDynamicTextButton(state, textOn, textOff, width, height, font, size, color)
local pressed = false
UiPush()
UiButtonPressDist(3)
UiFont(font, size)
UiButtonImageBox("ui/common/box-outline-6.png", 6, 6)
if state then
UiColor(unpack(color))
UiButtonHoverColor(color[1]*0.8, color[2]*0.8, color[3]*0.8)
if UiTextButton(textOn, width, height) then
state = not state
pressed = true
end
else
UiColor(1, 1, 1)
UiButtonHoverColor(0.8, 0.8, 0.8)
if UiTextButton(textOff, width, height) then
state = not state
pressed = true
end
end
UiPop()
return pressed, state
end
-- Draws a toggle button for boolean settings
local function drawBoolButton(setting)
UiPush()
UiAlign("left middle")
UiFont("regular.ttf", 22)
UiColor(0.9, 0.9, 0.025, 1)
UiText(setting.text, true)
UiTranslate(0, 15)
-- Set button color based on current state
if GetBool(setting.key) then
UiColor(0, 1, 0, 1) -- Green for ON
else
UiColor(1, 0, 0, 1) -- Red for OFF
end
UiFont("regular.ttf", 26)
if UiTextButton("Toggle", 150, 35) then
SetBool(setting.key, not GetBool(setting.key))
end
UiPop()
end
-- Draws the key assignment button
local function drawKeyAssignment(setting)
UiPush()
UiAlign("left middle")
UiFont("regular.ttf", 22)
UiColor(0.9, 0.9, 0.025, 1)
UiText(setting.text, true)
UiTranslate(0, 15)
local triggerKey = GetString(setting.keyAssignment.key)
local displayKey = triggerKey ~= "" and triggerKey or "Not Assigned"
local pressed, newState = drawDynamicTextButton(
false,
displayKey,
"Press A Key",
150,
35,
"regular.ttf",
26,
{1, 1, 1}
)
if pressed then
-- Wait for key input
local lastKey = InputLastPressedKey()
if lastKey and lastKey ~= "" and lastKey ~= "tab" and lastKey ~= "esc" then
SetString(setting.keyAssignment.key, lastKey)
end
end
UiPop()
end
-- Draws all UI elements
local function drawUI()
UiTranslate(UiCenter(), 100)
UiAlign("center middle")
UiFont("regular.ttf", 26)
UiButtonImageBox("ui/common/box-outline-6.png", 6, 6)
local spacing = 80
for _, setting in ipairs(modSettings) do
UiTranslate(0, spacing)
if setting.type == "bool" then
if setting.keyAssignment then
drawKeyAssignment(setting)
else
drawBoolButton(setting)
end
elseif setting.type == "int" then
-- Handle integer settings if any
DrawIntSlider(setting.key, setting.lower, setting.upper, setting.size, setting.text, setting.infinite)
end
end
-- Close button
UiTranslate(0, 100)
UiPush()
UiAlign("center middle")
UiFont("regular.ttf", 26)
UiColor(1, 1, 1, 1)
if UiTextButton("Close", 200, 40) then
Menu()
end
UiPop()
end
-- ==============================
-- Initialization and Main Loop
-- ==============================
function init()
initializeKeys()
end
function draw()
-- Center the UI horizontally and position it vertically with an offset
UiTranslate(UiCenter(), 0)
UiAlign("center middle")
drawUI()
end
-- ==============================
-- Additional Utility Functions
-- ==============================
-- Draws an integer slider (if needed in the future)
function DrawIntSlider(key, lowerBound, upperBound, size, text, infinite)
infinite = infinite or false
UiPush()
UiAlign("left middle")
UiFont("regular.ttf", 22)
UiColor(0.9, 0.9, 0.025, 1)
local value = GetInt(key)
if GetBool(key .. "_infinite") then
value = "Infinite"
end
UiText(text .. " " .. tostring(value), true)
UiColor(1, 1, 1, 1)
UiFont("regular.ttf", 26)
UiImageBox("box-solid-6.png", (upperBound * size) - (lowerBound * (size * 0.5)), 20, 5, 5)
UiTranslate(-((upperBound * (size * 0.5)) + (lowerBound * (size * 0.5))), 0)
local sliderValue = UiSlider("dot_small.png", "x", GetInt(key) * size, lowerBound * size, upperBound * size) / size
SetInt(key, sliderValue)
if infinite then
SetBool(key .. "_infinite", GetInt(key) == upperBound)
end
UiPop()
end
Modular Settings Configuration:
modSettings Table: All mod settings are defined in a table with their respective keys, descriptions, and types. This allows easy addition or modification of settings without altering the core logic.keyAssignment table, encapsulating the key name and default value.Enhanced setKey Function:
Initialization Process:
initializeKeys Function: Iterates through modSettings to initialize all keys, making the initialization process scalable.UI Rendering Enhancements:
drawDynamicTextButton Function: Simplified and made more flexible for different button states.drawBoolButton and drawKeyAssignment Functions: Separate functions to handle boolean toggles and key assignments, improving readability and maintenance.drawUI Function: Centralized UI rendering logic, looping through modSettings to create UI elements dynamically.Consistent UI Layout:
spacing variable to maintain consistent spacing between UI elements.UiAlign("left middle") for descriptive texts and buttons to align them properly.Future-Proofing:
type = "int") in the modSettings table, allowing easy expansion.Code Readability:
Extensibility: With the current structure, adding new settings (boolean, string, or integer) only requires adding new entries to the modSettings table. The UI will automatically render them accordingly.
Error Handling: Depending on the environment, consider adding error checks, especially when dealing with key inputs to prevent unexpected behaviors.
UI Enhancements: For a more polished UI, consider adding icons, tooltips, or grouping related settings into collapsible sections.
Performance: The current optimized code reduces redundancy and should perform efficiently. However, always test within the Teardown environment to ensure there are no performance bottlenecks.
This refactored code should be easier to maintain, extend, and understand. It streamlines the process of managing mod settings and enhances the user interface for a better experience.
Not yet included in a published release.