Skip to content
Open
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
1 change: 1 addition & 0 deletions changelog/snippets/other.7250.md
Original file line number Diff line number Diff line change
@@ -0,0 +1 @@
- All custom `String_` functions are moved to the default `string` library. Same pattern as the extended `table`. (#7250)
2 changes: 1 addition & 1 deletion lua/WeaponPriorities.lua
Original file line number Diff line number Diff line change
Expand Up @@ -18,7 +18,7 @@ function ParseTableOfCategories(inputString)

local ok, msg = pcall(
function()
local categories = StringSplit(inputString, ',')
local categories = string.split(inputString, ',')

for k, category in categories do
local clean = category
Expand Down
2 changes: 1 addition & 1 deletion lua/keymap/keymapper.lua
Original file line number Diff line number Diff line change
Expand Up @@ -452,7 +452,7 @@ function GetShiftAction(actionName, category)
end

function ContainsKeyModifiers(key)
return StringStarts(key, 'Shift') or StringStarts(key, 'Ctrl') or StringStarts(key, 'Alt')
return string.startsWith(key, 'Shift') or string.startsWith(key, 'Ctrl') or string.startsWith(key, 'Alt')
end

function KeyCategory(key, map, actions)
Expand Down
9 changes: 3 additions & 6 deletions lua/keymap/smartSelection.lua
Original file line number Diff line number Diff line change
Expand Up @@ -3,9 +3,6 @@
-- to bind this as a hotkey in your game.prefs make an action like this:
-- UI_Lua import("/lua/keymap/smartselection.lua").smartSelect("AIR MOBILE +idle -TRANSPORTATION -BOMBER")

local utils = import("/lua/system/utils.lua")


-- sets selection as per string expression
function smartSelect(strExpression)

Expand All @@ -25,7 +22,7 @@ end

-- sets selection as per compiled expression
function setSelection(expression)
local others = utils.StringJoin(expression.others, " ")
local others = string.join(expression.others, " ")

ConExecute("Ui_SelectByCategory " .. others)
local units = GetSelectedUnits()
Expand All @@ -46,10 +43,10 @@ function compile(strExpression)
result.others = {}
result.negatives = {}

local tokens = utils.StringSplit(strExpression, " ") -- split by space
local tokens = string.split(strExpression, " ") -- split by space
for k,v in tokens do

if utils.StringStarts(v, "-") then
if string.startsWith(v, "-") then
-- tokens with minus symbol are "negative"
local withoutSymbol = string.sub(v,2)
table.insert(result.negatives, withoutSymbol)
Expand Down
2 changes: 1 addition & 1 deletion lua/sim/MarkerUtilities.lua
Original file line number Diff line number Diff line change
Expand Up @@ -20,7 +20,7 @@
--** SOFTWARE.
--******************************************************************************************************

local StringSplit = import("/lua/system/utils.lua").StringSplit
local StringSplit = string.split
local TableDeepCopy = table.deepcopy

---@alias MarkerType 'Mass' | 'Hydrocarbon' | 'Spawn' | 'Start Location' | 'Air Path Node' | 'Land Path Node' | 'Water Path Node' | 'Ampibious Path Node' | 'Transport Marker' | 'Naval Area' | 'Naval Link' | 'Rally Point' | 'Large Expansion Area' | 'Expansion Area' | 'Protected Experimental Construction'
Expand Down
2 changes: 1 addition & 1 deletion lua/sim/ScenarioUtilities.lua
Original file line number Diff line number Diff line change
Expand Up @@ -704,7 +704,7 @@ function InitializeScenarioArmies()
local import = import
local GetArmyBrain = GetArmyBrain
local SetArmyEconomy = SetArmyEconomy
local StringStarts = StringStarts
local StringStarts = string.startsWith
local SetArmyFactionIndex = SetArmyFactionIndex
local SetArmyColorIndex = SetArmyColorIndex
local SetArmyAIPersonality = SetArmyAIPersonality
Expand Down
2 changes: 1 addition & 1 deletion lua/system/config.lua
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ end
metacleanup(nil)
metacleanup(false)
metacleanup(0)
metacleanup('')
--metacleanup('') -- string is cleaned up after the library is extended in `/lua/system/utils.lua`

--====================================================================================
-- Set up a metatable for coroutines (a.k.a. threads)
Expand Down
98 changes: 70 additions & 28 deletions lua/system/utils.lua
Original file line number Diff line number Diff line change
Expand Up @@ -646,13 +646,15 @@ end)
-- gfind was renamed to gmatch in Lua 5.1. added gmatch for additional compatibility
rawset(string, 'gmatch', string.gfind)

StringJoin = table.concat
--- Concatenates a list of strings into one, separated by `sep`. Alias of `table.concat`.
---@type fun(list: string[], sep?: string): string
string.join = table.concat

--- "explode" a string into a series of tokens, using a separator character `sep`
---@param str string
---@param sep? string Defaults to `:`
---@return string[]
function StringSplit(str, sep)
function string.split(str, sep)
sep = sep or ":"
local fields = {}
local pattern = string.format("([^%s]+)", sep)
Expand All @@ -663,24 +665,24 @@ end

--- Extracts a string between two specified strings
---
--- e.g. `StringExtract('/path/name_end.lua', '/', '_end', true)` --> name
--- e.g. `string.extractBetween('/path/name_end.lua', '/', '_end', true)` --> name
---@param str string
---@param from string
---@param to string
---@param fromEnd? boolean Defaults to `false`
---@return string?
function StringExtract(str, from, to, fromEnd)
function string.extractBetween(str, from, to, fromEnd)
local pattern = from .. '(.*)' .. to
if fromEnd then pattern = '.*' .. pattern end
local _, _, m = str:find(pattern)
return m
end

--- Adds comma as thousands separator in specified value
--- e.g. StringComma(10000) --> 10,000
--- e.g. string.commaFormat(10000) --> 10,000
---@param value number
---@return string
function StringComma(value)
function string.commaFormat(value)
local str = value or 0 ---@type number | string
while true do
local k
Expand All @@ -697,59 +699,71 @@ end
---@param str string
---@param symbol string? # Defaults to `" "`
---@return string
function StringPrepend(str, symbol)
function string.prepend(str, symbol)
if not symbol then symbol = ' ' end
return symbol .. str
end

--- Splits a string with camel case to a string with separate words
--- e.g. StringSplitCamel('SupportCommanderUnit') -> 'Support Commander Unit'
--- e.g. string.splitCamelCase('SupportCommanderUnit') -> 'Support Commander Unit'
---@param str string
---@return string
function StringSplitCamel(str)
function string.splitCamelCase(str)
local first = str:sub(1, 1)
local split = first .. str:sub(2):gsub("[A-Z]", StringPrepend)
local split = first .. str:sub(2):gsub("[A-Z]", string.prepend)
return (split:gsub("^.", string.upper))
end

--- Reverses order of letters for specified string
--- e.g. StringReverse('abc123') --> 321cba
---@param str string
---@return string
function StringReverse(str)
local tbl = {}
---@diagnostic disable-next-line: discard-returns
str:gsub(".", function(c) table.insert(tbl,c) end)
tbl = table.reverse(tbl)
return table.concat(tbl)

if not rawget(string, 'reverse') then
-- The Moho engine's Lua runtime is Lua 5.0, which predates `string.reverse` (a Lua 5.1
-- addition) -- see engine/Library.lua where it is explicitly annotated as absent. This
-- polyfill should be defined in the engine for performance if that ever changes.

--- Reverses order of letters for specified string
--- e.g. string.reverse('abc123') --> 321cba
---@param str string
---@return string
function string.reverse(str)
local tbl = {}
str:gsub(".", function(c) table.insert(tbl,c) end)
tbl = table.reverse(tbl)
return table.concat(tbl)
end
end

--- Capitalizes each word in specified string
--- e.g. StringCapitalize('hello supreme commander') --> Hello Supreme Commander
--- e.g. string.capitalize('hello supreme commander') --> Hello Supreme Commander
---@param str string
---@return string
function StringCapitalize(str)
function string.capitalize(str)
return string.gsub(" "..str, "%W%l", string.upper):sub(2)
end

---Check if a given string starts with specified string
---@param str string
---@param startString string
---@return boolean
function StringStarts(str, startString)
function string.startsWith(str, startString)
return str:sub(1, startString:len()) == startString
end

StringStartsWith = StringStarts

---Check if a given string ends with specified string
---@param str string
---@param endString string
---@return boolean
function StringEnds(str, endString)
function string.endsWith(str, endString)
return endString == '' or str:sub(-endString:len()) == endString
end

local name = type('')
local mmt = {
__newindex = function(_, key, _)
error(("Attempt to set attribute '%s' on %s"):format(tostring(key), name), 2)
end,
}
setmetatable(getmetatable(''), mmt)

--- Sorts two variables based on their numeric value or alpha order (strings)
function Sort(itemA, itemB)
if not itemA or not itemB then return 0 end
Expand Down Expand Up @@ -814,7 +828,7 @@ function GetCommandLineArgTable(option)
local result = {}
if args then
for _, arg in args do
local pair = StringSplit(arg, ":")
local pair = string.split(arg, ":")
local name, value = pair[1], pair[2]
result[name] = value
end
Expand Down Expand Up @@ -1143,4 +1157,32 @@ function vector_metatable.__mul(a, b)
a3 * b1 - a1 * b3,
a1 * b2 - a2 * b1
)
end
end

-- ==========================================================================================
-- * Deprecated aliases - kept for backwards compatibility with code that hasn't been
-- * updated to use the string library equivalents yet.
-- ==========================================================================================

---@deprecated Use `string.join` instead.
StringJoin = string.join
---@deprecated Use `string.split` instead.
StringSplit = string.split
---@deprecated Use `string.extractBetween` instead.
StringExtract = string.extractBetween
---@deprecated Use `string.commaFormat` instead.
StringComma = string.commaFormat
---@deprecated Use `string.prepend` instead.
StringPrepend = string.prepend
---@deprecated Use `string.splitCamelCase` instead.
StringSplitCamel = string.splitCamelCase
---@deprecated Use `string.reverse` instead.
StringReverse = string.reverse
---@deprecated Use `string.capitalize` instead.
StringCapitalize = string.capitalize
---@deprecated Use `string.startsWith` instead.
StringStarts = string.startsWith
---@deprecated Use `string.startsWith` instead.
StringStartsWith = string.startsWith
---@deprecated Use `string.endsWith` instead.
StringEnds = string.endsWith
2 changes: 1 addition & 1 deletion lua/ui/dialogs/createunit.lua
Original file line number Diff line number Diff line change
Expand Up @@ -1179,7 +1179,7 @@ function CreateDialog()
armyLabel = LOC('<LOC score_0003>Observer')
elseif armyData.civilian then
icon:SetSolidColor('aaaaaaaa')
armyLabel = StringCapitalize(armyData.nickname)
armyLabel = string.capitalize(armyData.nickname)
armyName = armyData.name == 'NEUTRAL_CIVILIAN' and LOC('<LOC lobui_0295>Neutral') or armyData.name
else -- human or AI army
armyLabel = CompressNickname(armyData.nickname, group.Width()-50)
Expand Down
3 changes: 0 additions & 3 deletions lua/ui/dialogs/eschandler.lua
Original file line number Diff line number Diff line change
Expand Up @@ -99,6 +99,3 @@ function HandleEsc(quit_game)
SelectUnits(nil)
end
end

-- kept for mod backwards compatibility
local Utils = import("/lua/system/utils.lua")
5 changes: 2 additions & 3 deletions lua/ui/game/gamemain.lua
Original file line number Diff line number Diff line change
Expand Up @@ -6,7 +6,6 @@
--* Copyright © 2005 Gas Powered Games, Inc. All rights reserved.
--*****************************************************************************

local utils = import("/lua/system/utils.lua")
local UIUtil = import("/lua/ui/uiutil.lua")
local LayoutHelpers = import("/lua/maui/layouthelpers.lua")
local Group = import("/lua/maui/group.lua").Group
Expand Down Expand Up @@ -365,7 +364,7 @@ function AdjustFrameRate()
if type(primaryAdapter) == 'string' then
if primaryAdapter ~= 'windowed' then
-- the value for the option is formatted as `width,height,fps`
local data = utils.StringSplit(primaryAdapter, ',')
local data = string.split(primaryAdapter, ',')
local hz = tonumber(data[3])
if hz then
fps = hz
Expand All @@ -375,7 +374,7 @@ function AdjustFrameRate()
-- can't use `Prefs` because `options_overrides` isn't stored in a profile
local allAdapterOptions = GetPreference('options_overrides.primary_adapter.custom.states')
for _, option in allAdapterOptions do
local data = utils.StringSplit(option.key, ',')
local data = string.split(option.key, ',')
local hz = tonumber(data[3])
if hz and hz > fps then
fps = hz
Expand Down
16 changes: 8 additions & 8 deletions lua/ui/lobby/ModsManager.lua
Original file line number Diff line number Diff line change
Expand Up @@ -561,7 +561,7 @@ function GetModNameVersion(mod)

-- remove old mod version from mod name
name = string.gsub(name, '[%[%<%{%(%s]+[vV]+%s*%d+[%.%d]*[%]%>%}%)%s]*', '')
name = StringCapitalize(name)
name = string.capitalize(name)
name = name:gsub("-", "", 1)

-- append new mod version to mod name
Expand All @@ -576,9 +576,9 @@ function GetModNameVersion(mod)
local ver = mod.version
-- correct mod version (e.g. 1.1.1 --> 1.11)
if string.find(ver, "%d%.%d%.%d") then
ver = StringReverse(ver)
ver = string.reverse(ver)
ver = ver:gsub("%.", "", 1)
ver = StringReverse(ver)
ver = string.reverse(ver)
elseif not string.find(ver, "%.") then
ver = ver .. '.0'
end
Expand All @@ -599,9 +599,9 @@ function GetModAuthor(mod)
if string.len(mod.author) < 20 then
author = mod.author
elseif string.find(mod.author, ",") then
author = StringSplit(mod.author, ',')[1]
author = string.split(mod.author, ',')[1]
elseif string.find(mod.author, " ") then
author = StringSplit(mod.author, ' ')[1]
author = string.split(mod.author, ' ')[1]
end
end
author = author:gsub("_", "", 1)
Expand Down Expand Up @@ -856,8 +856,8 @@ function LoadMods()
end

function StringReplace(str, remove, add)
local words = StringSplit(str, remove)
return StringJoin(words, add)
local words = string.split(str, remove)
return string.join(words, add)
end

-- refresh the mod list UI based on mods filtering and sorting
Expand Down Expand Up @@ -1167,7 +1167,7 @@ function CreateListElement(parent, mod, index)
group.desc.Bottom:Set(function() return group.check.Bottom() - LayoutHelpers.ScaleNumber(8) end)
group.desc.Height:Set(function() return group.desc.Bottom() - group.desc.Top() end)

local lines = StringSplit(mod.description, '\n')
local lines = string.split(mod.description, '\n')
if (table.getsize(lines) > 3) then
group.desc:SetText(lines[1] .. '\n' .. lines[2] .. '\n' .. lines[3])
elseif string.len(mod.description) > modInfoDesciptionMax then
Expand Down
10 changes: 5 additions & 5 deletions lua/ui/lobby/UnitsAnalyzer.lua
Original file line number Diff line number Diff line change
Expand Up @@ -707,11 +707,11 @@ function GetUnitsCategories(bp, showAll)
end
-- Ensures name of enhancements are nicely formatted
if cached.Enhancements[category] then
category = 'UPGRADE ' .. StringSplitCamel(category)
category = 'UPGRADE ' .. string.splitCamelCase(category)
end
if not CategoriesHidden[category] and
not StringStarts(category, 'BUILTBY') and
not StringStarts(category, 'DUMMY') then
not string.startsWith(category, 'BUILTBY') and
not string.startsWith(category, 'DUMMY') then
-- Ensures all categories have the same case
ret[string.upper(category)] = true
end
Expand Down Expand Up @@ -1056,7 +1056,7 @@ local function CacheEnhancement(key, bp, name, enh)
enh.Key = key
enh.Faction = bp.Faction
enh.Source = bp.Source
enh.SourceID = StringExtract(bp.Source, '/', '_unit.bp', true)
enh.SourceID = string.extractBetween(bp.Source, '/', '_unit.bp', true)

enh.Name = enh.Name or name
enh.Type = 'UPGRADE'
Expand Down Expand Up @@ -1154,7 +1154,7 @@ local function CacheUnit(bp)
-- and other enhancements have different stats and icons
-- depending on faction or whether they are for ACU or SCU
-- so store each enhancement with unique key:
local id = StringExtract(bp.Source, '/', '_unit.bp', true)
local id = string.extractBetween(bp.Source, '/', '_unit.bp', true)
local key = bp.Faction ..'_' .. id .. '_' .. name

CacheEnhancement(key, bp, name, enh)
Expand Down
1 change: 0 additions & 1 deletion lua/ui/lobby/UnitsManager.lua
Original file line number Diff line number Diff line change
Expand Up @@ -5,7 +5,6 @@
-- ==========================================================================================
local Mods = import("/lua/mods.lua")
local UIUtil = import("/lua/ui/uiutil.lua")
local Utils = import("/lua/system/utils.lua")
local Tooltip = import("/lua/ui/game/tooltip.lua")
local Group = import("/lua/maui/group.lua").Group
local Popup = import("/lua/ui/controls/popups/popup.lua").Popup
Expand Down
Loading