Compact: Difference between revisions

From Multi Theft Auto: Wiki
Jump to navigation Jump to search
(Created page with "{{Useful Function}} <lowercasetitle></lowercasetitle> __NOTOC__ '''Author:''' @FroPop This function create table containing variables and their values. ==Syntax== <syntaxhighlight lang="lua"> table compact(table Array, table/string Variable) </syntaxhighlight> ===Required Arguments=== * '''Array:''' the table handles it recursively. *'''Variable''': table or string takes a variable number of parameters. Each parameter can be either a string containing the n...")
 
No edit summary
Line 2: Line 2:
<lowercasetitle></lowercasetitle>
<lowercasetitle></lowercasetitle>
__NOTOC__
__NOTOC__
'''Author:''' @FroPop
This function create table containing variables and their values.
This function create table containing variables and their values.
==Syntax==
==Syntax==
Line 16: Line 14:


==Code==
==Code==
<section name="Author: @FroPop" class="both" show="true">
<syntaxhighlight lang="lua">
<syntaxhighlight lang="lua">
function compact(g, ...)
function compact(g, ...)
Line 30: Line 27:
end
end
</syntaxhighlight>
</syntaxhighlight>
</section>


==Example==
==Example==
Line 66: Line 62:
</syntaxhighlight>
</syntaxhighlight>
</section>
</section>
'''Author:''' @FroPop

Revision as of 23:21, 7 May 2022

This function create table containing variables and their values.

Syntax

table compact(table Array, table/string Variable)

Required Arguments

  • Array: the table handles it recursively.
  • Variable: table or string takes a variable number of parameters. Each parameter can be either a string containing the name of the variable, or an array of variable names. The array can contain other arrays of variable names inside it.

Returns

Returns the output table with all the variables added to it.

Code

function compact(g, ...)
    local args = {...}
    local tbl = {}
    g = g or _G
    for i, v in ipairs(args) do
        for w in string.gmatch(v, "[%w_]+") do
            tbl[v] = g[w]
        end
    end
    return tbl
end

Example

Click to collapse [-]
Shared Function

-- AND FORMAT FUNCTION --- With EXEMPLE
function format(s, tab)
    return (s:gsub('($%b{})', function(w) return tab[w:sub(3, -2)] or w end))
end

function compact(g, ...)
    local args = {...}
    local tbl = {}
    g = g or _G
    for i, v in ipairs(args) do
        for w in string.gmatch(v, "[%w_]+") do
            tbl[v] = g[w]
        end
    end
    return tbl
end

function testCompact()
   local tbl = {
       firstname = "Peter",
       lastname = "Griffin",
       age = 41
   }
   return format("My lastname is ${lastname} and age its ${age}", compact(tbl, "lastname",'age'))
end

outputChatBox( testCompact() )

Author: @FroPop