Aiuto:Manuale Scribunto/Lua

Da Cathopedia, l'enciclopedia cattolica.
Vai alla navigazione Vai alla ricerca

Data types

Lua è un linguaggio dynamically-typed, il che significa che le variabili e gli argomenti della funzione non hanno alcun tipo, solo i valori assegnati a loro. Tutti i valori portano al tipo.

Lua ha otto tipi di dati di base, ma solo sei sono rilevanti per l'estensione Scribunto. La funzione type () restituirà il tipo di un valore.

La funzione toString () converte un valore in una stringa. La funzione ToNumber () converte un valore in un numero se possibile, e altrimenti ritorna nil. Non ci sono funzioni esplicite per convertire un valore in altri tipi di dati.

I numeri vengono automaticamente convertiti in stringhe quando usati dove ci si aspetta una stringa, per esempio se utilizzati con l'operatore di concatenazione (..). Le stringhe riconosciute da ToNumber () vengono automaticamente convertite in numeri se utilizzate con operatori aritmetici. Quando si prevede un valore booleano, tutti i valori diversi da zero e falsi sono considerati come vero.

nil

nil è un tipo di dati pari a nullo, che esiste per rappresentare la mancanza di valore. Nil non può essere utilizzato come una chiave in una tabella, e non vi è alcuna differenza tra una chiave di tabella non assegnata e assegnata a valore nullo. Quando convertito in una stringa, il risultato è nullo. Una volta convertito in booleano, nil è considerato falso.

boolean

I valori booleani sono true e false.

Quando convertiti in una stringa, il risultato è true e false.

A differenza di molti altri linguaggi, in Lua i valori booleani non possono essere direttamente convertiti in numeri. Solo false e nil sono considerati falsi per la conversione booleano; il numero 0 e la stringa vuota sono entrambi considerati veri.

string

Le stringhe, in Lua, sono considerate una serie di byte di 8 bit; è compito dell'applicazione di interpretarle in qualsiasi codifica particolare.

Le stringhe letterali possono essere delimitate da un singolo o doppio apice ('o "); come JavaScript e diversamente da PHP, non vi è alcuna differenza. Sono riconosciute le seguenti sequenze escape:

  • \a (bell, byte 7)
  • \b (backspace, byte 8)
  • \t (horizontal tab, byte 9)
  • \n (newline, byte 10)
  • \v (vertical tab, byte 11)
  • \f (form feed, byte 12)
  • \r (carriage return, byte 13)
  • \" (double quote, byte 34)
  • \' (single quote, byte 39)
  • \\ (backslash, byte 92).

Le stringhe letterali possono essere anche definite utilizzando parentesi quadre.

-- Questa lunga stringa
foo = [[
bar\tbaz
]]

-- è equivalente alla stringa delimitata da apici
bar = 'bar\\tbaz\n'

Notare che tutte le stringhe sono considerate true quando convertite in booleano. Questo a differenza di molti altri linguaggi, in cui la stringa vuota è di solito considerato false.

number

Lua ha un solo tipo numerico, che in genere è rappresentato internamente come un valore in virgola mobile a doppia precisione. In questo formato, numeri interi compresi tra -9007199254740992 e 9007199254740992 possono essere rappresentati esattamente, mentre i numeri più grandi e numeri con una parte frazionaria possono subire di arrotondamento.

Le costanti numeriche sono specificate utilizzando un punto (.) come separatore decimale e senza separatori di raggruppamento, ad esempio 123456.78. I numeri possono anche essere rappresentati usando la notazione E (Esponente) senza spazi, ad esempio 1.23E-10, 123.45e20, o 1.23E5. Gli interi possono essere specificati in notazione esadecimale con un prefisso 0x, ad esempio 0x3A.

Anche se i Nan[1] e gli infiniti positivi e negativi siano correttamente conservati e trattati, Lua non fornisce letterali corrispondenti. La costante math.huge è infinito positivo, come lo è una divisione per zero (1/0 o 0/0), e possono essere utilizzati per generare rapidamente un NaN.

Notare che tutti i numeri sono considerati veri quando convertiti in booleano. Questo a differenza di molti altri linguaggi, in cui il numero 0 è di solito considerato falso. Quando sono convertiti in una stringa, numeri finiti sono rappresentati in decimale, possibilmente con E notazione; Nan è "nan" o "-nan"; e infiniti sono "inf" o "-inf".

table

Le tabelle Lua sono array associativi, molto simili agli array PHP e oggetti JavaScript.

Le tabelle sono create utilizzando le parentesi graffe. Una tabella vuota è {}. Per compilare i campi in fase di creazione, una lista di campi specifici può essere separata da virgole e/o punti e virgola entro le parentesi graffe. Questi prendono una delle diverse forme:

  • [expression1] = expression2 il primo valore dell'expression1 è usato come chiave. Il primo valore dell'expression2 come valore.
  • name = expression è equivalente a ["name"] = expression
  • expression è più o meno equivalente a [i] = expression, dove i è un intero a partire da 1 e incrementando con ogni campo specifico di questa formula. Se questo è l'ultimo campo identificatore e l'espressione ha più valori, vengono utilizzati tutti i valori; altrimenti solo la prima viene mantenuta.

I campi di una tabella sono accessibili usando le parentesi, per esempio table[key]. Le chiavi stringa, che possono essere anche nomi validi, sono accessibili anche usando la notazione punto, ad esempio, table.key è equivalente a di table['key']. La chiamata di una funzione, che è un valore nella tabella, può utilizzare la notazione tre punti (...), ad esempio table: func( ... ), che è equivalente a table['func']( table, ... ).

Una sequenza è una tabella con i valori non nil per tutti interi positivi da 1 a N e nessun valore nil per tutti gli interi positivi maggiori di N. Molte funzioni Lua operano solo su sequenze, e ignorano le chiavi intere non positive.

A differenza di molti altri linguaggi come PHP o JavaScript, qualsiasi valore, tranne nil e NaN[1], può essere utilizzato come chiave e non viene eseguita alcuna conversione di tipo. Queste sono tutte valide e distinte:


-- Create table
t = {}

t["foo"] = "foo"
t.bar = "bar"
t[1] = "one"
t[2] = "two"
t[3] = "three"
t[12] = "the number twelve"
t["12"] = "the string twelve"
t[true] = "true"
t[tonumber] = "yes, even functions may be table keys"
t[t] = "yes, a table may be a table key too. Even in itself."

-- This creates a table roughly equivalent to the above
t2 = {
   foo = "foo",
   bar = "bar",
   "one",
   "two",
   [12] = "the number twelve",
   ["12"] = "the string twelve",
   "three",
   [true] = "true",
   [tonumber] = "yes, even functions may be table keys",
}
t2[t2] = "yes, a table may be a table key too. Even in itself."

Analogamente, qualsiasi valore tranne nil può essere memorizzato come un valore in una tabella. La memorizzazione di nil equivale a cancellare la chiave dalla tabella, e accedendo ad una chiave che non è stata impostata provocherà un valore nullo.

Si noti che le tabelle non sono mai implicitamente copiate in Lua; se una tabella viene passata come argomento per la funzione e la funzione elabora le chiavi o valori nella tabella, tali modifiche saranno visibili nella chiamata.

Quando convertita in stringa, solitamente il risultato è "table", ma può essere sovrascritta con il __toString metamethod. Anche la tabella vuota è considerata vero come valore booleano.

function

Le funzioni in Lua sono valori di prima classe: possono essere creati in forma anonima, passati come argomenti, assegnati alle variabili, e così via. Le funzioni vengono create utilizzando la parola chiave function, e chiamate con parentesi. Lo Zucchero sintattico[2] è disponibile per le funzioni con nome, le funzioni locali e le funzioni che si comportano come funzioni membro di una tabella. Vedi più sotto i paragrafi Function declarations e Function calls per i dettagli.

Le funzioni Lua sono a chiusure (closure), il che significa che essi mantengono un riferimento al campo di applicazione in cui sono dichiarate e possono accedere e manipolare le variabili in questo ambito.

Come table", se una funzione viene assegnata ad una variabile differente o passata come argomento a un'altra funzione, mantiene sempre lo stesso "oggetto funzione" che verrà chiamato.

Quando convertito in una stringa, il risultato è sempre "function".

Tipi non supportati

Il tipo di userdata è utilizzato per contenere valori non definiti per le estensioni a Lua scritti in altre lingue; per esempio, un userdata potrebbe essere utilizzato per contenere un puntatore C o struct. Per consentire l'uso di Scribunto in ambienti Hosting dove il codice di compilazione personalizzato non è consentito, non vengono utilizzate tali estensioni. Il tipo di thread rappresenta il puntatore per coroutine, che non sono disponibili in sandbox di Scribunto.

Metatables

Ogni tabella può avere una tabella associata nota come Metatables. I campi nel Metatables sono utilizzati da alcuni operatori e funzioni per specificare un comportamento diverso o di ripiego per la tabella. Il Metatables è accessibile da una tabella utilizzando la funzione Metatables e impostata con la funzione setmetatable(). Quando si accede alle loro meta-funzioni, i campi Metatables sono accessibili con rawget().

I campi Metatables che influenzano la tabella stessa sono:

__index
è usato quando un accesso tabella t [key] fosse tornato a zero. Se il valore di questo campo è una tabella, l'accesso sarà ripetuto in tale tabella, vale a dire __index[key] (che può invocare __index della tabella del metatables). Se il valore di questo campo è una funzione, la funzione verrà chiamato come __index( t, key ). La funzione rawget() bypassa questo metamethod.
__newindex
è usato quando si assegna una key a una tabella t[key] = value, dove rawget( t, key ) sarebbe tornato a zero. Se il valore di questo campo è una tabella, l'assegnazione sarà ripetuta in tale tabella, ad esempio __newindex[key] = value (che può invocare __newindex della tabella del metatable ). Se il valore di questo campo è una funzione, la funzione verrà chiamata come __newindex( t, key, value ). La funzione rawset() bypassa questo metamethod.
__call
è utilizzato quando la sintassi chiamata di funzione viene utilizzata in una tabella, t( ··· ). Il valore deve essere una funzione, chiamata similmente __call( t, ··· ).
__mode
è usato per creare tabelle con riferimenti deboli (weak references). Il valore deve essere una stringa. Per default, qualsiasi valore utilizzato come chiave o come valore in una tabella non sarà Garbage collection[3]. Se questo metafield contiene la lettera k, le chiavi possono essere Garbage Collection se non ci sono riferimenti deboli (weak references), e se contiene il valore V possono esserlo; in ogni caso, sia la chiave e il valore corrispondente vengono rimossi dalla tabella. Si noti che il comportamento è indefinito se questo campo viene alterato dopo che la tabella è utilizzata come metatable.

Altri campi MetaTable includono:

a Per gli operatori binari, Lua legge gli argomenti MetaTable prima a sinistra, nel caso, allora da destra quando si cerca un metamethod da usare.
b Per gli operatori relazionali, il metamethod viene utilizzato solo se la stessa funzione è specificata in entrambi gli argomenti della metatables. Diverse funzioni anonime, anche con corpo e chiusura identici, non possono essere considerati gli stessi.
c __metatable incide sia getmetatable() sia setmetatable()

Nota: In Lua, anche tutte le stringhe condividono una singola metatable, in cui __index si riferisce alla string della tabella. Questa metatable non è accessibile in Scribunto e non é il riferimento alla string della tabella; la tabella di stringhe a disposizione dei moduli è una copia.

Variables

Le variabili sono spazi che memorizzano i valori. Ci sono tre tipi di variabili in Lua:

  • variabili globali
  • variabili locali
  • campi tabella

name rappresenta una variabile globale o locale (o un argomento di funzione, che è solo una specie di variabile locale). Le variabili sono sempre globali se non esplicitamente dichiarata come locale utilizzando local. Qualsiasi variabile alla quale non è stato assegnato un valore è considerata avere un valore nil.

Le variabili globali sono memorizzate in una tabella standard Lua chiamato environment; questa tabella è spesso disponibile come variabile globale _G. È possibile impostare un metatable per questa variabile globale tabella; __index e __newindex metamethod sarà chiamato per accessi e assegnazioni delle variabili globali, proprio come farebbero per accessi e assegnazioni di campi in qualsiasi altra tabella.

L'ambiente per una funzione può essere accessibile tramite la funzione getfenv() e modificato utilizzando la funzione setfenv(); in Scribunto, queste funzioni sono fortemente limitate se sono disponibili a tutti. Le variabili locali sono a visibilità lessicale (lexically scoped); vedi Local variable declarations per i dettagli.

Expressions

Expressions è un qualcosa che ha dei valori:

  • letterali (numeri, stringhe, vero, falso, nil)
  • dichiarazioni di funzioni anonime
  • costruttori di tabella
  • riferimenti variabili
  • chiamate di funzione, i varargs espressione, espressioni tra parentesi
  • operatori unari applicati ad espressioni
  • espressioni combinate con operatori binari.

La maggior parte delle espressioni hanno un valore; chiamate di funzione e possono avere qualsiasi numero. Si noti che avvolgendo una chiamata di funzione o un varargs espressione tra parentesi perderà tutto tranne il primo valore.

exp-list sono elenchi separati da virgole di espressioni. Tutti, tranne l'ultima espressione sono forzati ad un valore (valori aggiuntivi che decadono, o che utilizzano nil se l'espressione non ha valori); tutti i valori dall'ultima espressione sono inclusi nei valori dell'elenco di espressioni.

Operatori aritmetici

Lua supporta i soliti operatori aritmetici: addizione, sottrazione, moltiplicazione, divisione, modulo, potenza e negazione.

Quando tutti gli operandi sono numeri o stringhe per i quali tonumber() ritorna non-nill, le operazioni hanno il loro significato abituale.

Se uno degli operandi è una tabella con un appropriato metamethod, il metamethod sarà richiamato.

Operatore Funzione Esempio Metamethod Note
+ Addizione a + b __add
- Sottrazione a - b __sub
* Moltiplicazione a * b __mul
/ Divisione a / b __div Divisioni per zero non sono errori, ma ritornate come NaN[1] o infinito.
% Modulo a % b __mod Definito come a % b == a - math.floor( a / b ) * b.
^ Potenza a ^ b __pow Non sono ammessi esponenti non interi.
- Negazione -a __unm

Operatori relazionali

Gli operatori relazionali in Lua sono i seguenti: == , ~ = , < , > , <= e > = . Il risultato di un operatore relazionale è sempre di tipo booleano.

Il simbolo di uguaglianza ( == ) confronta prima i tipi degli operandi; se sono diversi, il risultato è false. Poi confronta i valori: nil, booleano, numero e stringa vengono confrontati nel modo previsto. Le funzioni sono uguali se fanno riferimento all'oggetto stesso della funzione esatta; function() end == function() end restituirà falso, in quanto è il confronto di due diverse funzioni anonime. Le tabelle di default sono confrontate allo stesso modo, ma questo può essere cambiato con __eq metamethod.

La disuguaglianza ( ~= ) restituisce esattamente il contrario di uguaglianza.

Per l'ordinamento degli operatori, se entrambi sono numeri o entrambi sono stringhe, sono confrontati direttamente. Successivamente, vengono controllati i metamethods:

  • a < b usa __lt
  • a <= b usa __le, se disponibile, o se __lt è disponibile, allora è considerato equivalente a not ( b < a )
  • a> b è considerato equivalente a b <a
  • a> = b è considerato equivalente a b <= a

Se i metamethods necessari non sono disponibili, viene generato un errore.

Operatori booleani

Gli operatori booleani sono and , or e not . Tutti utilizzano l'interpretazione standard in cui nil e false sono considerati falso e qualsiasi altro valore è considerato vero.

Per and, se l'operando di sinistra è considerato false, allora esso è ritornato e il secondo operando non viene valutato; altrimenti viene restituito il secondo operando.

Per or , se l'operando di sinistra è considerata true, allora esso è ritornato e il secondo operando non viene valutato; altrimenti il secondo operando viene restituito.

Per not , il risultato è sempre true o false.

Si noti che and e or sono a valutazione corto circuito, cioè il secondo operando viene valutato unicamente se il valore del primo operando non è sufficiente da solo a determinare il risultato dell'operatore. Ad esempio, foo() or bar() chiamerà solo bar() se foo() restituisce false o nil come primo valore.

Operatore di concatenazione

L'operatore di concatenazione è simboleggiato da due punti (..), utilizzati come a .. b . Se entrambi gli operandi sono numeri o stringhe, vengono convertite in stringhe e concatenate. In caso contrario, se un __concat metamethod è disponibile, viene utilizzato. Altrimenti, viene generato un errore.

Si noti che le stringhe Lua sono immutabili e Lua non fornisce alcun tipo di "costruttore stringa", quindi un ciclo che fa ripetutamente a = a .. b dovrà creare una nuova stringa per ogni iterazione e alla fine Garbage collection[3] delle vecchie stringhe. Se serve concatenare numerose stringhe, può essere più opportuno usare string.format() o inserire tutte le stringhe in un sequence e utilizzare table.concat() alla fine.

Operatore lunghezza

L'operatore lunghezza è #, utilizzato come #a . Se a è una stringa, restituisce la lunghezza in byte. Se a è un sequence tabella, restituisce la lunghezza della sequenza.

Se a è una tabella che non è una sequenza, il #a può restituire qualsiasi valore N tale che a [N], non è nil e un [N+1] è pari a nil, anche se ci sono valori non-nil a indici più elevati. Per esempio,

-- Questa non è una sequenza, perché a[3] è nil e a[4] non è
a = {1, 2, nil, 4}

-- Questa può restituire entrambi 2 o 4.
-- E questo può cambiare anche se la tabella non viene modificata.
mw.log (#A)

Precedenza tra operatori

Precedenza tra gli operatori di Lua, dal più alto al più basso:

  • ^
  • not # - (negation)
  • * / %
  • + - (subtraction)
  • ..
  • < > <= >= ~= ==
  • and
  • or

All'interno di un livello di precedenza, la maggior parte degli operatori binari sono left-associative, per esempio a + b + c viene interpretato come (a + b) + c. L'elevamento a potenza e la concatenazione sono right-associative, per esempio a ^ b ^ c viene interpretato come a ^ (b ^ c).

function calls

Le chiamate di funzione in Lua assomigliano a quelle della maggior parte degli altri linguaggi: un nome seguito da un elenco di argomenti tra parentesi:

func( expression-list )

Come di consueto con le liste di espressione in Lua, l'ultima espressione della lista può fornire molteplici valori degli argomenti.

Se la funzione viene chiamata con un minor numero di valori nella expression-list di quanto siano gli argomenti nella definizione della funzione, gli argomenti in più avranno valore nil. Se la expression-list contiene più valori di quanti siano gli argomenti, i valori in eccesso sono scartati. È anche possibile per una funzione ricevere un numero variabile di argomenti; vedi Function declarations per i dettagli.

Lua permette anche la chiamata diretta di un valore di ritorno di funzione, per esempio func()(). Se un'espressione più complessa rispetto a un accesso di variabile, è necessario determinare la funzione da chiamare, un'espressione tra parentesi può essere usata al posto della variabile di accesso.

Lua è zucchero sintattico (syntactic sugar[2]) per due casi comuni. Il primo è quando una tabella viene utilizzata come un oggetto, e la funzione deve essere chiamata come metodo sull'oggetto. La sintassi:

table:name( expression-list )

è esattamente equivalente a

table.name( table, expression-list )

La seconda causa comune è il metodo di attuazione named arguments facendo passare una tabella contenente le mappature name-to-value come l'unico argomento posizionale alla funzione. In questo caso, le parentesi della lista degli argomenti possono essere omesse. Questo funziona anche se la funzione deve essere passata come una singola stringa letterale. Ad esempio, le chiamate

func{ arg1 = exp, arg2 = exp }
func"string"

sono equivalenti a

func( { arg1 = exp, arg2 = exp } )
func( "string" 

Queste possono essere combinate; le seguenti chiamate sono equivalenti:

table:name{ arg1 = exp, arg2 = exp }
table.name( table, { arg1 = exp, arg2 = exp } )

Function declarations

La sintassi per dichiarare una funzione è simile al seguente:

function ( var-list )
    block
end

Tutte le variabili in var-list sono locali alla funzione, con i valori assegnati dalla lista espressione nel function call. Addizionali variabili locali possono essere dichiarate all'interno del block.

Quando la funzione viene chiamata, le istruzioni in block vengono eseguite, dopo le variabili locali corrispondenti a var-list vengono create e ad esse assegnati i valori. Se un return statement viene raggiunto, il blocco viene chiuso e il valore dell'espressione chiamata di funzione sono quelli dell'istruzione di ritorno. Se l'esecuzione raggiunge la fine del blocco della funzione senza incontrare una dichiarazione di ritorno, il risultato dell'espressione chiamata di funzione ha valori zero.

Le funzioni Lua sono a chiusura lessicale lexical closures. Un linguaggio comune è quello di dichiarare le variabili "statiche private" ​​come locali nel campo in cui viene dichiarata la funzione. Per esempio:

-- This returns a function that adds a number to its argument
function makeAdder( n )
    return function( x )
        -- The variable n from the outer scope is available here to be added to x
        return x + n
    end
end

local add5 = makeAdder( 5 )
mw.log( add5( 6 ) )
-- restituisce 11

Una funzione può essere dichiarata per accettare un numero variabile di argomenti, specificando ... come elemento finale nel var-list:

function ( var-list, ... )
    block
end

All'interno del blocco, l'espressione varargs ... può essere utilizzata, con il risultato di tutti i valori in più nella chiamata di funzione. Per esempio,

local join = function ( separator, ... )
    -- get the extra arguments as a table
    local args = { ... }
    -- get the count of extra arguments, correctly
    local n = select( '#', ... )
    return table.concat( args, separator, 1, n )
end

join( ', ', 'foo', 'bar', 'baz' )
-- returns the string "foo, bar, baz"

La funzione select() è progettata per funzionare con l'espressione varargs; in particolare, select( '#', ... ) dovrebbe essere usato al posto di #{ ... } per contare il numero di valori nell'espressione varargs.

Lua permette con lo zucchero sintattico (syntactic sugar[2]) di combinare dichiarazioni di funzioni e l'assegnazione ad una variabile; vedi Function declaration statements per i dettagli.

Si noti che questo non funziona:

local factorial = function ( n )
    if n <= 2 then
        return n
    else
        return n * factorial( n - 1 )
    end
end

Dal momento che la dichiarazione di funzione viene elaborata prima che l'istruzione di assegnazione variabile locale sia completa,factorial all'interno del corpo della funzione si riferisce alla variabile (probabilmente non definita) di quel nome in un ambito esterno. Questo problema può essere evitato dichiarando la variabile locale prima e poi assegnandola in una dichiarazione successiva, oppure utilizzando la sintassi function declaration statement.

Statements

Uno statements è l'unità base di esecuzione: un incarico, struttura di controllo, chiamata di funzione, dichiarazione di variabile, ecc...

Un chunk è una sequenza di istruzioni, opzionalmente separate da un punto e virgola. Un chunk è fondamentalmente considerato il corpo di una funzione anonima, in modo che possa dichiarare le variabili locali, ricevere gli argomenti e valori restituiti.

Un block è anche una sequenza di istruzioni, proprio come un pezzo. Un blocco può essere delimitato per creare una singola istruzione: do block end. I block possono essere utilizzati per limitare la portata delle variabili locali, o per aggiungere un return o un break nel bel mezzo di un altro blocco.

Assignments

variable-list = expression-list

variable-list è un elenco di variabili separato da virgole; expression-list è un elenco di una o più espressioni separato da virgole. Tutte le espressioni vengono valutate prima di eseguire qualunque assegnazione, quindi a, b = b, a will swap the values of a and b.

Local variable declarations

local variable-list

local variable-list = expression-list

Le variabili locali possono essere dichiarate ovunque all'interno di un block o chunk. La prima forma, senza una lista di espressioni, dichiara le variabili, ma non assegna un valore in modo che tutte le variabili hanno nil come valore. La seconda forma assegna valori alle variabili locali, come descritto sopra in Assignments.

Si noti che la visibilità della variabile locale inizia con l'istruzione dopo la dichiarazione della variabile locale. Quindi una dichiarazione come local x = x dichiara una variabile locale x e assegna ad essa il valore di x dal campo di applicazione esterna. La variabile locale rimane nel campo di applicazione fino alla fine del blocco più interno, contenente la dichiarazione di variabile locale.

Control structures

while exp do block end

L'istruzione while ripete un blocco finché l'espressione restituisce un valore vero.

repeat block until exp

Il comando repeat ripete un blocco fino a quando un espressione restituisce un valore vero. Le variabili locali dichiarate all'interno del blocco sono accessibili nell'espressione.

for name = exp1, exp2, exp3 do block end
'for name = exp1, exp2 do block end

Questa prima forma del ciclo for dichiarerà una variabile locale, e ripete il blocco per i valori da exp1 a exp2 aggiungendo exp3 ad ogni iterazione. Si noti che exp 3 può essere omesso del tutto, in questo caso viene utilizzato 1, ma i valori non numerici, come nil e false restituiscono errore. Tutte le espressioni vengono valutate una volta prima di avviare il ciclo.

Questa forma del ciclo for è più o meno equivalente a

do
    local var, limit, step = tonumber( exp1 ), tonumber( exp2 ), tonumber( exp3 )
    if not ( var and limit and step ) then error() end
    while ( step > 0 and var <= limit ) or ( step <= 0 and var >= limit ) do
        local name = var
        block
        var = var + step
    end
end

tranne le variabili var, limit e step che non sono accessibili in qualsiasi altro luogo. Si noti che la variabile name è locale al blocco; per utilizzare il valore dopo il ciclo, deve essere copiata in una variabile dichiarata fuori del ciclo.


for var-list in expression-list do block end

La seconda forma del ciclo for funziona con funzioni di iteratozionw. Come nella prima forma, il expression-list viene valutata solo una volta prima di iniziare il ciclo. Questa forma del ciclo for è più o meno equivalente a

do
    local func, static, var = expression-list
    while true do
        local var-list = func( static, var )
        var = var1  -- var1 is the first variable in var-list
        if var == nil then break end
        block
    end
end

ancora una volta le variabili, tranne variables func, static, e var, non sono accessibili in qualsiasi altro luogo. Si noti che le variabili in var-list sono locali al blocco; per usarle dopo il ciclo, devono essere copiate in variabili dichiarate al di fuori del ciclo.

Spesso espressione-list è una singola chiamata di funzione che restituisce i tre valori. Se la funzione di iterazione può essere scritta in modo che dipende solo dai parametri passati in esso, allora sarebbe la più efficiente. In caso contrario, Programming in Lua suggerisce che una chiusura deve essere preferita per restituire una tabella come variabile statica e aggiornare i suoi campi ad ogni iterazione.

if exp1 then block1 elseif exp2 then block2 else block3 end

Esegue block1 se exp1 restituisce true, altrimenti esegue block2 se exp2 restituisce true e block3 in caso contrario. La porzione else block3 può essere omessa, e la porzione elseif exp2 then block2 se necessario può essere ripetuta o omessa.

return expression-list

L'istruzione return viene utilizzata per restituire i valori da una funzione o da un chunk (che è solo una funzione). expression-list è un elenco separato da virgole, di zero o più espressioni.

Lua implementa tail calls[4]: se expression-list consiste esattamente di un'espressione che è una chiamata di funzione, lo stack frame[5] corrente verrà riutilizzato per la chiamata a tale funzione. Questo ha implicazioni per le funzioni che si occupano dello stack di chiamate (call stack[6]), come ad esempio getfenv() e debug.traceback().


L'istruzione return deve essere l'ultima istruzione nel suo block. Se per qualche motivo è necessario un ritorno al centro di un blocco, un blocco esplicito do return end può essere usato.

break

L'istruzione break viene utilizzata per terminare l'esecuzione di un while di ripetizione, o per un ciclo, saltando alla successiva istruzione dopo il ciclo.

L'istruzione break deve essere l'ultima istruzione nel suo block. Se per qualche motivo è necessaria una pausa nel mezzo di un block, un blocco esplicito do break end può essere utilizzato.

Function calls as statements

Una chiamata di funzione può essere utilizzata come istruzione; in questo caso, la funzione viene chiamata solo per eventuali effetti collaterali e può avere ad esempio mw.log() valori di registro e tutti i valori di ritorno vengono scartati.

Function declaration statements

Lua offre uno "zucchero sintattico[2]" per dichiarare una funzione e assegnarla ad una variabile più naturale. Le seguenti coppie di dichiarazioni sono equivalenti:

-- Basic declaration
function func( var-list ) block end
func = function ( var-list ) block end
-- Local function
local function func( var-list ) block end
local func; func = function ( var-list ) block end
-- Function as a field in a table
function table.func( var-list ) block end
table.func = function ( var-list ) block end
-- Function as a method in a table
function table:func( var-list ) block end
table.func = function ( self, var-list ) block end

Si notino i "due punti" (:) per chiamate di funzione, l'aggiunta di un argomento implicito chiamato "self" all'inizio della lista argomenti.

Error handling

Gli errori possono essere "eliminati" utilizzando le funzioni error() e assert(). Per "catturare" gli errori, usare pcall() o xpcall(). Si noti che alcuni errori interni Scribunto non possono essere catturati in codice Lua.

Standard libraries

Le librerie standard Lua forniscono servizi essenziali e le funzioni di performance-critical per Lua. Qui sono documentate solo quelle parti delle librerie standard che sono disponibili in Scribunto.

Garbage collection

Lua esegue la gestione automatica della memoria. Questo significa che il programmatore no si deve preoccupare né dell'allocazione di memoria per i nuovi oggetti né di liberarla quando gli oggetti non sono più necessari. Lua gestisce la memoria automaticamente eseguendo un garbage collector di tanto in tanto per raccogliere tutti gli oggetti "morti" (cioè, gli oggetti che non sono più accessibili da Lua) e gli oggetti che sono raggiungibili solo tramite weak references. Tutta la memoria usata da Lua è soggetta a gestione automatica: tabelle, funzioni, stringhe, ecc...

Garbage collection parte automaticamente, e non può essere configurato all'interno di Scribunto.

Basic functions

_G

Questa variabile contiene un riferimento all'attuale tabella delle variabili globali; la variabile globale foo può anche essere letta come _G.foo. Si noti, tuttavia, che non c'è niente di speciale riguardo a _G; essa può essere inserita nello stesso modo in qualsiasi altra variabile:

foo = 1
mw.log( foo ) -- logs "1"
_G.foo = 2
mw.log( foo ) -- logs "2"
_G = {}       -- _G no longer points to the global variable table
_G.foo = 3
mw.log( foo ) -- still logs "2"

La tabella variabile globale può essere usata come qualsiasi altra tabella. Per esempio:

-- Chiamare una funzione il cui nome è memorizzato in una variabile
_G[var]()
-- Accedere a nomi e a valori di stringa di tutte le variabili globali
for k, v in pairs( _G ) do
   mw.log( k, v )
end
-- Accedere alla creazione di nuove variabili globali
setmetatable( _G, {
    __newindex = function ( t, k, v )
         mw.log( "Creation of new global variable '" .. k .. "'" )
         rawset( t, k, v )
    end
} )

_VERSION

Una stringa contenente la versione in esecuzione di Lua, ad esempio, "Lua 5.1".


assert

assert( v, message, ... ) Se v è nil o false, restituisce un errore. In questo caso, message viene utilizzato come testo dell'errore: se nil (o non specificato), il testo è "assertion failed!"; se una stringa o un numero, il testo è il valore stesso; altrimenti l'asserzione stessa genererà un errore.

Se v è un qualsiasi altro valore, restituisce tutti gli argomenti, tra cui v e message.

Un linguaggio piuttosto comune in Lua è, per una funzione, la restituzione di un valore "true" nel funzionamento normale, e in caso di errore ritorna nil o false come primo valore e un messaggio di errore come secondo valore. Un semplice controllo degli errori può quindi essere implementato includendo la chiamata in una chiamata assert:

-- Questo non fa controlli di errori
local result1, result2, etc = func( ... )

-- Questo funziona allo stesso, ma controlla gli errori
local result1, result2, etc = assert( func( ... ) )

error

error( message, level )

Genera un errore con testo message.

error normalmente aggiunge alcune informazioni circa la posizione dell'errore. Se level è 1 o omesso, allora l'informazione è la posizione della chiamata a error itself; 2 utilizza la posizione della chiamata della funzione che ha richiamato l'errore; e così via. Passando 0 omette l'inserimento delle informazioni sulla posizione.

getfenv

getfenv( f )

Nota che questa funzione potrebbe non essere disponibile, dipendentemente da allowEnvFuncs nella configurazione del motore.

Restituisce una condizione (variabile globale tabella) come specificato da f:

  • Se 1, nil, o omesso, restituisce la condizione della funzione chiamante getfenv. Spesso questo sarà uguale a _G.
  • Interi 2-10 ritornano la condizione di funzioni superiori nel call stack[6]. Ad esempio, 2 restituisce la condizione della funzione che chiama la funzione corrente, 3 restituisce la condizione della funzione che chiama tale funzione, e così via. Un errore viene generato se il valore è superiore al numero di chiamate di funzione nello stack, o se il livello mirato di stack restituito con una tail call[4].
  • Passando una funzione restituisce la condizione che verrà utilizzata quando viene chiamata quella funzione.

Gli ambienti utilizzati da tutte le funzioni di libreria standard e funzioni di libreria Scribunto sono protetti. Il tentativo di accedere a questi ambienti utilizzando getfenv restituirà nil.

getmetatable

getmetatable( table )

Restituisce il metatable di una tabella. Qualsiasi altro tipo è restituito nil. Se il metatable ha una __metatable di campo, tale valore verrà restituito al posto del metatable reale.

ipairs

ipairs( t )

Restituisce tre valori: una funzione di iterazione, la tabella t, e 0. Questo è destinato all'uso in iterator form of for:

for i, v in ipairs( t ) do
    block
end

Iterazione sulle coppie ( 1, t[1] ), ( 2, t[2] ), e così via, fermandosi quando t [i] sarà nil.

Il comportamento standard può essere ignorato, fornendo un __ipairs metamethod. Se esiste tale metamethod, la chiamata a ipairs restituirà i tre valori restituiti da __ipairs( t ).

next

next( table, key )

Questo consente l'iterazione delle chiavi in una tabella. Se key è nil o non specificato, restituisce la prima chiave nella tabella e il suo valore; in caso contrario, restituisce chiave "next" e il suo valore. Quando non sono più disponibili chiavi, restituisce nil. È possibile verificare se una tabella è vuota utilizzando l'espressione next( t ) == nil.

Si noti che l'ordine in cui vengono restituite le chiavi non è specificato, anche per le tabelle con indici numerici. Per scorrere una tabella in ordine numerico, usare numerical for or ipairs.

Il comportamento, quando si utilizza next per lo scorrimento, è indefinito se, a ogni chiave inesistente viene assegnato un valore. L'assegnazione di un nuovo valore (compreso nil) a un campo esistente è permesso.

pairs

pairs( t )

Restituisce tre valori: una funzione di iterazione (next o un work-alike[7]), la tabella t, e nil. Questo è destinato all'uso nei moduli iteratori di for:

for k, v in pairs( t ) do
    block
end

Questo codice itara sulle coppie chiave-valore in t come farebbe next; consultare la documentazione relativa next per le restrizioni sulla modifica della tabella durante lo scorrimento.

Il comportamento standard può essere ignorato, fornendo un __pairs metamethod. Se esiste questo metamethod, la chiamata a coppie restituirà i tre valori restituiti da __pairs( t ).

pcall

pcall( f, ... )

Chiama la funzione f con gli argomenti dati in protected mode (modalità protetta). Ciò significa che se viene generato un errore durante la chiamata a f, pcall restituirà false e il messaggio di errore sollevato. Se non si verifica alcun errore, pcall ritornerà true e tutti i valori restituiti dalla chiamata.

In pseudocode, pcall può essere definito similmente a come segue:

function pcall( f, ... )
    try
        return true, f( ... )
    catch ( message )
        return false, message
    end
end

rawequal

rawequal( a, b )

Questo equivale a a == b tranne che ignora qualsiasi __eq metamethod.

rawget

rawget( table, k )

Questo equivale a table[k] tranne che ignora qualsiasi __index metamethod.

rawset

rawset( table, k, v )

Questo equivale a table[k] = v tranne che ignora qualsiasi __newindex metamethod.

select

select( index, ... )

Se index è un numero, restituisce tutti gli argomenti a ... dopo tale indice. Se index è una stringa '#', restituisce il numero di argomenti in ....

In altre parole, select è qualcosa di più o meno come il successivo, tranne che funzionerà correttamente anche quando ... contiene valori nil (si veda la documentazione per # and unpack per il problema con i nil).

function select( index, ... )
    local t = { ... }
    if index == '#' then
        return #t
    else
        return unpack( t, index )
    end
end

setmetatable

setmetatable( table, metatable )

Imposta il metatabella di un tavolo. ' metatabella </ code>' può essere pari a zero, ma devono essere fornite in modo esplicito.

Se il metatable corrente ha un __metatable field, setmetatable viene generato un errore.

Imposta il metatable di una table. metatable può esser nil, ma deve essere fornito in modo esplicito.

tonumber

tonumber( value, base )

Tenta di convertire value in un numero. Se è già un numero o una stringa convertibile in un numero, allora tonumber restituisce questo numero; altrimenti, restituisce nil.

base (di default 10) Specifica la base per interpretare il numerale. La base può essere un qualsiasi numero intero compreso tra 2 e 36, inclusi. Prendendo ad esempio il default 10, la lettera "A" (in entrambi i casi superiore o inferiore) rappresenta il 10, "B" rappresenta l'11, e così via, con "Z" che rappresenta 35.

In base 10, il valore può avere una parte decimale, essere espresso in notazione E, e può avere un "0x" ad indicare di base 16. In altre basi, solo numeri interi senza segno sono accettati.

tostring

tostring( value )

Converte value in una stringa. Vedere Data types sopra per i dettagli su come ciascun tipo viene convertito.

Il comportamento standard per le tabelle può essere ignorato, fornendo un __tostring metamethod. Se esiste questo metamethod, la chiamata a tostring restituirà il valore singolo restituito da __tostring( value ).

type

type( value )

Restituisce il tipo value come una stringa: "nil", "number", "string", "boolean", "table", or "function".

unpack

unpack( table, i, j )

Restituisce i valori dalla tabella riportata, qualcosa come table[i], table[i+1], ···, table[j] come farebbe se scritto manualmente. Se nil o non inserito, i default 1 e j default #table.

Si noti che i risultati non sono deterministici se table non è un sequence e j è nil o non specificato; vedi Length operator per i dettagli.

xpcall

xpcall( f, errhandler )

Questo è molto simile a pcall, tranne che il messaggio di errore viene passato alla funzione errhandler prima di essere restituito.

In pseudocode, xpcall potrebbe essere definito qualcosa di simile a questo:

function xpcall( f, errhandler )
    try
        return true, f()
    catch ( message )
        message = errhandler( message )
        return false, message
    end
end

Debug library

debug.traceback

debug.traceback( message, level )

Restituisce una stringa con la traccia del call stack[6]. Una stringa di messaggio opzionale viene aggiunta all'inizio della traceback. Un numero di livello opzionale dice a quale livello di stack per avviare il traceback.

Math library

math.abs

math.abs( x )

Ritorna il valore assoluto di x.

math.acos

math.acos( x )

Ritorna l'arco coseno di x (in radianti).

math.asin

math.asin( x )

Ritorna l'arcoseno x (in radianti).

math.atan

math.atan( x )

Ritorna l'arco tangente di x (in radianti).

math.atan2

math.atan2( y, x )

Ritorna l'arco tangente di y/x (in radianti), utilizzando i segni di entrambi i parametri per trovare la quadrante del risultato.

math.ceil

math.ceil( x )

Restituisce il più piccolo intero maggiore o uguale a di x.

math.cos

math.cos( x )

Ritorna il coseno di x (in radianti).

math.cosh

math.cosh( x )

Restituisce il coseno iperbolico di x.

math.deg

math.deg( x )

Ritorna l'angolo x (in radianti) in gradi.

math.exp

math.exp( x )

Ritorna il valore <math>e^x</math>.

math.floor

math.floor( x )

Restituisce il più grande intero minore o uguale a x.

math.fmod

math.fmod( x, y )

Restituisce il resto della divisione di x by y che arrotonda il quoziente allo zero.

math.frexp

math.frexp( x )

Restituisce due valori m e e in modo tale che:

  • Se x è finito e non-zero: <math>x = m \times 2^e</math>, e è un numero intero, e il valore assoluto di m è nella gamma <math>[0.5, 1)</math>
  • Se x è pari a zero: m e e sono 0
  • Se x è NaN[1] o infinito: m è x e e non è specificato

math.huge

Il valore che rappresenta l'infinito positivo; maggiore o uguale a qualsiasi altro valore numerico.

math.ldexp

math.ldexp( m, e )

Ritorna <math>m \times 2^e</math> (e deve essere un numero intero).

math.log

math.log( x )

Ritorna il logaritmo naturale di x.

math.log10

math.log10( x )

Restituisce il logaritmo in base 10 di x.

math.max

math.max( x, ... )

Restituisce il valore massimo tra i suoi argomenti.

Il comportamento con NaN[1] non è specificato. Con l'implementazione corrente NaN verrà restituito se x è NaN, ma qualsiasi altro NaN sarà ignorato.

math.min

math.min( x, ... )

Restituisce il valore minimo tra i suoi argomenti.

Il comportamento con NaN[1] non è specificato. Con l'implementazione corrente, NaN verrà restituito se x è NaN, ma qualsiasi altro NaN sarà ignorato.

math.modf

math.modf( x )

Restituisce due numeri, la parte integrale di x e la parte frazionaria di x.

math.pi

Il valore di <math>\pi</math>.

math.pow

math.pow( x, y )

Equivalente a x^y.

math.rad

math.rad( x )

Restituisce l'angolo x (in gradi) in radianti.

math.random

math.random( m, n )

Restituisce un numero pseudo-casuale.

Gli argomenti m e n può essere omesso, ma se specificato deve essere convertibile in numeri interi.

  • Senza argomenti, restituisce un numero reale nel range <math>[0,1)</math>
  • Con un argomento, restituisce un numero intero nel range <math>[1,m]</math>
  • Con due argomenti, restituisce un numero intero nel range <math>[m,n]</math>

math.randomseed

math.randomseed( x )

Imposta x come il seed per il generatore pseudo-casuale.

Si noti che usando lo stesso seed causerà math.random per l'uscita della stessa sequenza di numeri.

math.sin

math.sin( x ) Restituisce i seno di x (in radianti).

math.sinh

math.sinh( x )

Restituisce il seno iperbolico di x.

math.sqrt

math.sqrt( x )

Restituisce la radice quadrata di x. Equivalente a x^0.5.

math.tan

math.tan( x )

Restituisce la tangente di x (in radianti).

math.tanh

math.tanh( x )

Restituisce la tangente iperbolica di x.

Operating system library

os.clock

os.clock()

Restituisce un'approssimazione del valore in secondi dal tempo della CPU utilizzati dal programma.

os.date

os.date( format, time )

Linguaggio librerie formatDate possono essere utilizzati per la formattazione più completa data

Restituisce una stringa o una tabella contenente la data e l'ora, formattate in base al format. Se il formato viene omesso o nil, viene utilizzato "%c".

Se time è valorizzato sarà formattato (vedi os.time()). In caso contrario, viene utilizzata l'ora corrente.

Se format inizia con '!', allora la data è formattata in UTC[8]

Dopo questo carattere facoltativo, se il formato è la stringa "*t", allora la data restituisce una tabella con i seguenti campi:

  • year (anno completo)
  • month (mese 1–12)
  • day (giorno 1–31)
  • hour (ora 0–23)
  • min (minuti 0–59)
  • sec (secondi 0–60)
  • wday (giorni della settimana, Domenica è 1)
  • yday (numero del giorno dell'anno)
  • isdst (ora legale, un valore booleano; può essere assente se le informazioni non sono disponibili)

Se il formato non è "*t", allora la data restituisce la data come una stringa, formattata secondo le stesse regole della funzione C strftime.

os.difftime

os.difftime( t2, t1 )

Restituisce il numero di secondi da t1 a t2.

os.time

os.time( table )

Restituisce un numero che rappresenta l'ora corrente.

Quando viene chiamato senza argomenti, restituisce l'ora corrente. Se passato a una tabella, il tempo codificato nella tabella verrà analizzato. La tabella deve avere i campi "year", "month", and "day", e può anche includere "hour" (default 12), "min" (default 0), "sec" (default 0), e "isdst".

Package library

require

require( modulename )

Carica il modulo specificato.

Per primo appare in package.loaded[modulename] per vedere se il modulo è già caricato. Se è così, restituisce package.loaded[modulename].

In caso contrario, richiama ogni caricatore nella sequenza package.loaders per tentare di trovare un caricatore per il modulo. Se viene trovato un caricatore, allora è chiamato un caricatore. Il valore restituito dal caricatore viene memorizzato in package.loaded[modulename] e viene restituito.

Vedere la documentazione di package.loaders per informazioni sui caricatori disponibili.

Si noti che ogni modulo richiesto viene caricato nell'ambiente sandbox, quindi non può esportare le variabili globali, come a volte è fatto in Lua 5.1. Invece, tutto ciò che il modulo intende esportare dovrebbe essere incluso nella tabella restituita dal modulo.

Per esempio, se si ha un modulo "Module:Giving" contenente:

local p = {}

p.someDataValue = 'Hello!'

return p

È possibile caricarlo in un altro modulo con codice come questo:

local giving = require( "Module:Giving" )

local value = giving.someDataValue -- value is now 'Hello!'

package.loaded

Questa tabella contiene i moduli caricati. Le chiavi sono i nomi dei moduli, ed i valori sono i valori restituiti quando il modulo è stato caricato.

package.loaders

Questa tabella contiene la sequenza delle funzioni di ricerca utilizzare per il caricamento dei moduli. Ogni funzione di ricerca viene chiamata con un singolo argomento, il nome del modulo da caricare. Se viene trovato il modulo, la ricerca deve restituire una funzione che in realtà carica il modulo e restituire il valore da restituire per require. Altrimenti, deve restituire nil.

Scribunto fornisce due funzioni di ricerca:

  1. Cerca in package.preload[modulename] per la funzione di caricamento
  2. Cerca in modules provided with Scribunto

per il nome del modulo, e se fallisce cerca nel modulo: namespace. : "Modulo": deve essere fornita prefisso (prefix must be provided)

Si noti che i caricatori standard di Lua sono nil inclusi.

package.preload

Questa tabella contiene le funzioni da caricare, usate dal primo ricercatore Scribunto comprese in package.loaders.

package.seeall

package.seeall( table )

Imposta l'__index metamethod per table di _G.

String library

In tutte le funzioni di stringa, il primo carattere è in posizione 1, non la posizione 0 come in C, PHP e JavaScript. Gli indici possono essere negativi, nel qual caso vengono contati dalla fine della stringa: posizione -1 è l'ultimo carattere della stringa, -2 è il penultimo, e così via.

La libreria stringa assume la codifica dei caratteri di un byte. Essi non sono in grado di gestire i caratteri Unicode. Per operare su stringhe Unicode, utilizzare i metodi corrispondenti nella Scribunto Ustring library.

string.byte

string.byte( s, i, j )

Se la stringa è considerata come un array di byte, restituisce i valori di byte per s[i], s[i+1], ···, s[j].

Il valore di default per i è 1; Il valore di default per j è i. Uguale a mw.ustring.byte().

string.char

string.char( ... )

Riceve zero o più numeri interi. Restituisce una stringa di lunghezza pari al numero di argomenti, in cui ogni carattere ha il valore di byte uguale al suo argomento corrispondente. Vedere mw.ustring.char() per una funzione simile che utilizza Unicode codepoints[9] piuttosto che valori di byte.

string.find

Controllare la traduzione di questa sezione string.find( s, pattern, init, plain )

Looks for the first match of pattern in the string s. If it finds a match, then find returns the offsets in s where this occurrence starts and ends; otherwise, it returns nil. If the pattern has captures, then in a successful match the captured values are also returned after the two indices.

Un terzo argomento numerico opzionale init specifica dove cominciare la ricerca; il suo valore predefinito è 1 e può essere negativo. Un valore true come quarto, argomento opzionale plain disattiva lo schema di corrispondenza, quindi la funzione "trova la sottostringa", senza caratteri in pattern è considerato "magico".

Si noti che se è dato plain, allora pure init deve essere dato.

Vedere mw.ustring.find()] per una funzione simile estesa come descritto in Ustring patterns e dove la init offset[10] è in caratteri piuttosto che byte.

string.format

string.format( formatstring, ... )

Restituisce una versione formattata del suo numero variabile di argomenti a seguito della descrizione fatta nel suo primo argomento (che deve essere una stringa).


La stringa di formato utilizza un sottoinsieme limitato di printf identificatori di formato:

  • Iflag riconosciuti sono '-', '+', ' ', '#', e '0'.
  • Sono supportate larghezze campo intero fino a 99. '*' non è supportato.
  • Precisioni interi fino a 99 sono supportati. '*' non è supportato.
  • Modificatori di lunghezza non sono supportati.
  • Indicatori di conversione riconosciuti sono 'c', 'd', 'i', 'o', 'u', 'x', 'X', 'e', 'E', 'f', 'g', 'G', 's', '%', e la non-standard 'q'.
  • specificatori posizionali (ad esempio "%2$s") non sono supportati.


Lo specificatore di conversione q è come s, ma formatta la stringa in una forma adatta per essere riletta sicuramente dall'interprete Lua: la stringa è scritta tra virgolette, e tutti i doppi apici, a capo, gli zeri incorporati, e backslash nella stringa sono correttamente tralasciati quando utilizzati.

La conversione tra stringhe e numeri viene eseguita come specificato in Data types; altri tipi non vengono convertiti automaticamente in stringhe. Le stringhe contenenti caratteri NUL (valore byte 0) non sono adeguatamente trattati.

Identico a mw.ustring.format().

string.gmatch

string.gmatch( s, pattern )

Restituisce una funzione iteratrice che, ogni volta che viene chiamata, restituisce le successive catture da pattern sulla stringa s. Se pattern specifica non cattura, poi tutta la corrispondenza viene prodotta in ogni chiamata.

Per questa funzione, un ^ all'inizio di un pattern non è magico, perché ciò impedirebbe l'iterazione. È trattato come un carattere letterale.

Vedere mw.ustring.gmatch() una funzione similare per il quale il modello viene esteso come descritto in Ustring patterns.

string.gsub

string.gsub( s, pattern, repl, n )

Restituisce una copia di s in cui tutte (o la prima n, se data) le occorrenze del pattern sono state sostituite da una stringa di sostituzione specificata da repl, che può essere una stringa, una tabella o una funzione. gsub restituisce anche, come il suo secondo valore, il numero totale di corrispondenze che si sono verificate.

Se repl è una stringa, allora il suo valore è usato per la sostituzione. Il carattere % funziona come un carattere escape: qualsiasi sequenza in repl del modulo %n, con n compreso tra 1 e 9, si distingue per il valore di n-esima stringa catturata. La sequenza di %0 resta per l'intera corrispondenza, e la sequenza %% è sinonimo di un singolo %.

Se repl è una tabella, allora la tabella viene interrogata per ogni corrispondenza, utilizzando la prima acquisizione come chiave; se il modello (pattern) non specifica alcuna acquisizione, allora l'intera partita viene utilizzata come chiave.

Se repl è una funzione, allora questa funzione viene chiamata ogni volta che si verifica una corrispondenza, con tutte le corrispondenti sottostringhe passate in ordine come argomenti. Se il modello (pattern) non specifica alcuna corrispondenza, allora tutta la corrispondenza viene passata come un unico argomento.

Se il valore restituito dalla tabella query o dalla chiamata della funzione, è una stringa o un numero, allora è usato come stringa di sostituzione; altrimenti, se è false o nil, allora non c'è sostituzione (cioè, la corrispondenza originale è conservata nella stringa).

Vedere mw.ustring.gsub() per una funzione simile in cui il modello viene esteso come descritto in Ustring patterns.

string.len

string.len( s ) Restituisce la lunghezza della stringa, in byte. Non è confuso da caratteri ASCII NUL. Equivalente a #s.

Vedere mw.ustring.len() per una funzione simile utilizzando codepoints[9] Unicode anziché byte.

string.lower

string.lower( s )

Restituisce una copia di questa stringa con tutte le lettere maiuscole ASCII cambiate in caratteri minuscoli. Tutti gli altri caratteri sono lasciate invariati.

Per una funzione simile, in cui tutti i caratteri maiuscoli con le definizioni in minuscoli vengono convertiti in Unicode.

string.match

string.match( s, pattern, init )

Guarda la prima corrispondenza di pattern nella stringa. Se ne trova una, allora match restituisce la cattura del pattern; altrimenti restituisce nil. Se pattern specifica non cattura, allora tutta la partita viene restituita.

Un terzo argomento numerico opzionale init specifica dove cominciare la ricerca; il suo valore predefinito è 1 e può essere negativo.

Vedere mw.ustring.match() per una funzione simile in cui il modello (pattern) viene esteso come descritto in Ustring patterns e lo slittamento init è in caratteri piuttosto che byte.

string.rep

string.rep( s, n )

Restituisce una stringa che è la concatenazione di n copie della stringa s. Identico a mw.ustring.rep().

string.reverse

string.reverse( s )

Restituisce una stringa che è la stringa s invertita (byte per byte).

string.sub

string.sub( s, i, j )

Restituisce la stringa di s che inizia da i e continua fino a j; i e j possono essere negativi. Se j è nil o omesso, -1 viene utilizzato.

In particolare, la chiamata string.sub(s,1,j) restituisce un prefisso s con la lunghezza j e string.sub(s, -i) restituisce un suffisso s con la lunghezza i.

Vedere mw.ustring.sub() per una funzione simile in cui gli offset sono caratteri piuttosto che byte.

string.upper

string.upper( s )

Restituisce una copia di questa stringa di caratteri ASCII minuscoli, cambiata in maiuscoli. Tutti gli altri caratteri sono lasciati invariati.

Vedere mw.ustring.upper() per una funzione simile. Unicode.

Patterns

Si noti che i modelli di Lua sono simili a espressioni regolari, ma non sono identici. In particolare, notare le seguenti differenze di espressioni regolari e PCRE:

  • Il carattere citato è percentuale (%), non backslash (\).
  • Dot (.) corrisponde sempre a tutti i caratteri, tra cui a capo.
  • Non modo non sensibile alle maiuscole.
  • No alternanza (operatore |).
  • Quantificatori (*, +, ?, e -) possono essere applicati solo a singoli caratteri o classi di caratteri, non per catturare gruppi.
  • L'unico quantificatore "non avido" (greedy) è -, che è equivalente al quantificatore *? del PCRE.
  • No quantificatore finito generalizzato (ad esempio il quantificatore {n,m} in PCRE).
  • Le uniche asserzioni di lunghezza zero sono ^, $ e %f[set] modello frontier; affermazioni come quelle di PCRE \b or (?=···) non sono presenti.
  • I modelli stessi non riconoscono i caratteri escape come '\ddd'. Tuttavia, dal momento che i modelli sono strings questo genere di escape possono essere utilizzati nelle stringhe letterali utilizzate per creare lo schema corde.

Si noti inoltre che un modello non può contenere incorporato zero byte (ASCII NUL, "\0"). Utilizzare invece %z.

Vedere anche Ustring patterns per un sistema di pattern-matching simile, utilizzando caratteri Unicode.

Character class

Una classe di caratteri viene usata per rappresentare un insieme di caratteri. Le seguenti combinazioni sono consentite nel descrivere una classe di caratteri: non è un carattere magico

  • x: (dove x non è un metacarattere (magico) ^$()%.[]*+-?) rappresenta solo il carattere x.
  • .: (a dot) rappresenta tutti i caratteri.
  • %a: rappresenta tutte le lettere ASCII.
  • %c: rappresenta tutti i caratteri di controllo ASCII.
  • %d: rappresenta tutte le cifre.
  • %l: rappresenta tutte le lettere minuscole ASCII.
  • %p: rappresenta tutti i caratteri di punteggiatura.
  • %s: rappresenta tutti i caratteri di spazio ASCII.
  • %u: rappresenta tutte le lettere maiuscole ASCII.
  • %w: rappresenta tutti i caratteri alfanumerici ASCII.
  • %x: rappresenta tutte le cifre esadecimali.
  • %z: rappresenta ASCII NUL, zero byte.
  • %A: tutti i caratteri non compresi in %a.
  • %C: tutti i caratteri non compresi in %c.
  • %D: tutti i caratteri non compresi in %d.
  • %L: tutti i caratteri non compresi in %l.
  • %P: tutti i caratteri non compresi in %p.
  • %S: tutti i caratteri non compresi in %s.
  • %U: tutti i caratteri non compresi in %u.
  • %W: tutti i caratteri non compresi in %w.
  • %X: tutti i caratteri non compresi in %x.
  • %Z: tutti i caratteri non compresi in %z.
  • %x: (Dove x è un qualsiasi carattere non alfanumerico) rappresenta il carattere x. Questo è il modo standard per sfuggire i metacaratteri (magici). Qualsiasi carattere di punteggiatura (anche non magico) può essere preceduto da un % quando viene utilizzato per rappresentare se stesso in un modello.
  • [set]: rappresenta la classe che è l'unione di tutti i caratteri di set. Un intervallo di caratteri può essere specificato separando i caratteri del range, con un -. Tutte le classi %x sopra descritto può essere utilizzato anche come componente di set. Tutti gli altri caratteri di set rappresentano se stessi. Ad esempio, [%w_] (o [_%w]) rappresentano tutti i caratteri alfanumerici più il carattere di sottolineatura, [0-7] rappresenta le cifre in sistema numerico ottale, e [0-7%l%-] rappresenta le cifre ottali più le lettere minuscole più il carattere -. L'interazione tra le gamme e le classi non è definita. Pertanto, modelli (pattern) come [%a-z] o [a-%%] non hanno alcun significato.
  • [^set]: rappresenta il complemento di set, dove set viene interpretato come sopra.
Pattern items

Un pattern item può essere:

  • Una singola classe di caratteri, che corrisponde a qualsiasi singolo carattere nella classe;
  • Una singola classe di caratteri seguita da *, che corrisponde a 0 o più ripetizioni di caratteri nella classe. Questi elementi di ripetizione saranno sempre corrispondenti alla sequenza più lunga possibile;
  • Una singola classe di caratteri seguita da +, che corrisponde a 1 o più ripetizioni di caratteri nella classe. Questi elementi di ripetizione saranno sempre corrispondenti alla sequenza più lunga possibile;
  • Una singola classe di caratteri seguita da -,che corrisponde anche a 0 o più ripetizioni di caratteri della classe. A differenza di *, questi elementi di ripetizione corrispondono sempre alla sequenza più breve possibile;
  • Una singola classe di caratteri seguita da ?, che corrisponde a 0 o a 1 occorrenza di un carattere nella classe;
  • %n, per n compreso tra 1 e 9; tale elemento corrisponde a una sottostringa uguale all'ennesima stringa catturata (vedi sotto);
  • %bxy, dove x e y sono due caratteri distinti; tale elemento corrisponde a stringhe che iniziano con x, termina con y, e dove x e y sono equilibrate. Ciò significa che, se si legge la stringa da sinistra a destra, contando +1 per una x e -1 per una y, la y finale è il primo y dove il conteggio raggiunge 0. Per esempio, l'elemento %b() corrisponde espressioni con parentesi bilanciate.
  • %f[set], The set set is interpreted as previously described. The beginning and the end of the subject are handled as if they were the character '\0'.
    Note that frontier patterns were present but undocumented in Lua 5.1, and officially added to Lua in 5.2. The implementation in Lua 5.2.1 is unchanged from that in 5.1.0.
  • Un modello di frontiera (frontier pattern); tale voce corrisponde a una stringa vuota in qualsiasi posizione tale che il carattere successivo appartiene a set e il carattere precedente non appartiene a set. La serie set viene interpretata come descritto in precedenza. L'inizio e la fine del soggetto vengono gestiti come se fossero il carattere '\0'.
Pattern

Un pattern è una sequenza di elementi del modello (pattern).

Un ^ all'inizio di un modello àncora la corrispondenza all'inizio della stringa soggetto. Un $ alla fine di un modello, àncora la corrispondenza alla fine della stringa soggetto. In altre posizioni, ^ e $ non hanno alcun significato speciale e rappresentano se stessi.

Captures

Un modello (pattern) può contenere sotto-modelli racchiusi fra parentesi; essi descrivono le catture (captures). Quando una corrisponda è trovata, le sottostringhe della stringa soggetto, che corrispondono alla cattura, vengono memorizzate ("catturate") per un utilizzo futuro.

le captures sono numerate in base alle loro parentesi di sinistra. Per esempio, nel modello (a*(.)%w(%s*)), la parte della stringa corrispondente a*(.)%w(%s*) viene memorizzata come la prima cattura (e quindi ha il numero 1); la corrispondenza carattere . viene catturata con il numero 2, e la parte corrispondente %s* ha il numero 3.

I riferimenti di capture possono comparire nella stessa stringa modello, e fanno riferimento al testo che è stato catturato in precedenza nella corrispondenza. Ad esempio, ([a-z])%1 corrisponderà ad una qualsiasi coppia di identiche lettere minuscole, mentre ([a-z])([a-z])([a-z])[a-z]%3%2%1 corrisponderà a qualsiasi 7-lettera palindromo.

Come caso particolare, la captures vuota () cattura la posizione stringa corrente (un numero). Per esempio, se applichiamo il modello "()aa()" sulla stringa "flaaap", ci saranno due acquisizioni: 3 e 5.

Table library

La maggior parte delle funzioni della Table library presuppongono che la tabella rappresenta una sequence.

Le funzioni table.foreach(), table.foreachi() e table.getn() potrebbero essere disponibile, ma sono deprecate. Utilizzare un ciclo for con pairs(), un ciclo for con ipairs(), e l'operatore di lunghezza.

table.concat

table.concat( table, sep, i, j )

Dato un array in cui tutti gli elementi sono stringhe o numeri, restituisce table[i] .. sep .. table[i+1] ··· sep .. table[j].

Il valore predefinito per sep è una stringa vuota, il valore predefinito per i è 1 e il valore predefinito per j è la lunghezza della tabella. Se i è maggiore di j, restituisce una stringa vuota.

table.insert

table.insert( table, value )
table.insert( table, pos, value )

Se necessario inserire l'elemento value alla posizione pos in table, spostando su altri elementi per aprire spazio. Il valore predefinito per pos è la lunghezza della tabella più 1, in modo che un table.insert(t, x) inserisce x alla fine della tabella t.

Elementi fino a #table sono spostati; vedi Length operator per avvertimenti se la tabella non è un sequence.

table.maxn

table.maxn( table )

Restituisce il più grande indice numerico positivo della tabella data, oppure zero se la tabella non ha indici numerici positivi.

Per fare questo, itera sull'intera tabella. Questo è più o meno equivalente a:

function table.maxn( table )
    local maxn, k = 0, nil
    repeat
        k = next( table, k )
        if type( k ) == 'number' and k > maxn then
            maxn = k
        end
    until not k
    return maxn
end

table.remove

table.remove( table, pos )

Rimuove da table l'elemento nella posizione pos, scalando, se necessario, altri elementi per riempire lo spazio lasciato. Restituisce il valore dell'elemento rimosso. Il valore predefinito per pos è la lunghezza della tabella, in modo che una chiamata di table.remove( t ) rimuove l'ultimo elemento di tabella t.

Gli elementi fino a #table sono spostati; vedi Length operator per avvertimenti se la tabella non è un sequence.

table.sort

table.sort( table, comp )

Ordina gli elementi di una tabella in un dato ordine, nella tabella stessa, da table[1] a table[#table]. Se comp è dato, allora deve essere una funzione che riceve due elementi di una tabella, e restituisce true quando il primo è minore del secondo (in modo che not comp(a[i+1],a[i]) sarà true dopo l'ordinamento). Se comp non è dato, allora l'operatore standard di Lua < viene usato al suo posto.

L'algoritmo di ordinamento non è stabile; cioè, gli elementi considerati uguali dall'ordine indicato, potrebbero avere le loro posizioni relative cambiate da quell'ordinamento.

Scribunto libraries

Tutte le librerie Scribunto si trovano nella tabella mw.

Base functions

mw.allToString

mw.allToString( ... )

Richiama tostring() su tutti gli argomenti, poi li concatena con le schede come separatori.

mw.clone

mw.clone( value )

Crea una copia completa di un valore. Tutte le tabelle (e le loro metatables) sono ricostruite ex-novo. Le funzioni, però, sono ancora condivise.

mw.getCurrentFrame

mw.getCurrentFrame()

Restituisce il frame object corrente.

mw.incrementExpensiveFunctionCount

mw.incrementExpensiveFunctionCount() Aggiunge uno al conto della "expensive parser function" (limite massimo delle chiamate parser superato) e genera un'eccezione se si supera il limite.

Vedi $wgExpensiveParserFunctionLimit).

mw.isSubsting

mw.isSubsting()

Restituisce true se l'#invoke corrente è substed (Aiuto:subst, altrimenti false. Vedi sopra Returning text per la discussione sulle differenze sottostringa o no sottostringa.

mw.loadData

mw.loadData( module )

A volte un modulo ha bisogno di grandi tabelle di dati; per esempio, un modulo polivalente, per convertire le unità di misura, potrebbe necessitare di una grande tabella di unità riconosciute e i loro coefficienti di conversione. E a volte questi moduli saranno utilizzati più volte in una sola pagina. L'analisi della tabella grandi dimensioni di dati per ogni {{#invoke:}} può usare una notevole quantità di tempo. Per evitare questo problema, è fornito mw.loadData() .

mw.loadData funziona come require(), con le seguenti differenze:

  • Il modulo caricato viene valutato solo una volta per pagina, piuttosto che una volta per chiamata di {{#invoke:}}.
  • Il modulo caricato non viene registrato in package.loaded.
  • Il valore restituito dal modulo caricato deve essere una tabella. Altri tipi di dati non sono supportati.
  • La tabella restituita (e tutte le sottotabelle) possono contenere solo booleani, numeri, stringhe e altre tabelle. Altri tipi di dati, in particolare le funzioni, non sono ammessi.
  • La tabella restituita (e tutte le sottotabelle) non possono avere una metatable.
  • Tutte le chiavi della tabella devono essere booleani, numeri o stringhe.
  • La tabella di fatto restituita da mw.loadData() ha metamethods che forniscono accesso in sola lettura alla tabella restituita dal modulo. Dal momento che non contiene direttamente i dati, pairs() and ipairs() funziona, ma altri metodi, tra cui #value, next(), e le funzioni in Table library, non funzionerà correttamente.

L'ipotetico modulo unità di conversione di cui sopra potrebbe conservare il suo codice nella sezione "Module:Convert" e i suoi dati in "Module:Convert/data", e "Module:Convert" avrebbe utilizzato local data = mw.loadData( 'Module:Convert/data' ) per caricare in modo efficiente i dati.

mw.dumpObject

mw.dumpObject( object )

Serializza object per una rappresentazione leggibile, quindi restituisce la stringa risultante.

mw.log

mw.log( ... )

Passa gli argomenti a mw.allToString(), quindi aggiunge la stringa risultante per il buffer di registro.

Nella console di debug, la funzione print() è un alias per questa funzione.

mw.logObject

mw.logObject( object )
mw.logObject( object, prefix )

Richiama mw.dumpObject() e aggiunge la stringa risultante per il buffer di registro. Se prefix è dato, verrà aggiunto al buffer di registro seguito prima da un segno di uguale la stringa serializzata viene aggiunta (vale a dire il testo registrato sarà "prefix = object-string").

Frame object

L'oggetto frame è l'interfaccia per i parametri passati a {{#invoke:}}, e per il parser.

frame.args

Una tabella per accedere gli argomenti passati al parser (analisi). Ad esempio, se un modulo è chiamato da wikitext con

{{#invoke:module|function|arg1|arg2|name=arg3}}

allora frame.args[1] restituirà "arg1", frame.args[2] restituirà "arg2", e frame.args['name'] (o frame.args.name) ritorneranno "arg3". È anche possibile iterare su argomenti utilizzando pairs( frame.args ) o ipairs( frame.args ).

Si noti che i valori in questa tabella sono sempre stringhe; tonumber(), se necessario, può essere usato per convertirli in numeri. Le chiavi, tuttavia, sono numeri, anche se esplicitamente fornite nel invocazione: {{#invoke:module|function|1|2=2}} dà valori di stringa "1" e "2" indicizzato per chiavi numeriche 1 e 2.

Come nei template di invocazione di MediaWiki, gli argomenti nominati avranno spazi vuoti iniziali e finali rimossi entrambi dal nome e dal valore prima di essere passati a Lua, mentre gli argomenti senza nome non hanno spazi rimossi.

Per motivi di prestazioni, frame.args utilizza una metatabella, piuttosto che contienere direttamente gli argomenti. I valori degli argomenti sono richiesti da MediaWiki su richiesta. Ciò significa che la maggior parte degli altri metodi di tabella non funziona correttamente, tra cui #frame.args, next( frame.args ), e le funzioni nel Table library.

Se la sintassi del preprocessore come invocazioni di template e gli argomenti in tripla-parentesi sono inclusi all'interno di un argomento per #invoke, saranno espansi prima di essere passati a Lua. Se alcuni tag speciali scritti in notazione XML, come ad esempio <pre>, <nowiki>, <gallery> and <ref>, sono inclusi come argomenti per #invoke, allora questi tag verranno convertiti in "strip marker" - stringhe speciali che iniziano con un carattere di delete (ASCII 127) - a essere sostituiti con HTML dopo che sono restituiti dal #invoke.

frame:callParserFunction

frame:callParserFunction( name, args )
frame:callParserFunction( name, ... )
frame:callParserFunction{ name = string, args = table }

notare l'utilizzo di named arguments.

Richiama una funzione parser, restituendo una stringa appropriata. Quando possibile, le funzioni native Lua o le funzioni di libreria Scribunto dovrebbero essere preferiti a questa interfaccia.

Le seguenti chiamate sono approssimativamente equivalenti al wikitext indicato:

-- {{ns:0}}
frame:callParserFunction{ name = 'ns', args = 0 }

-- {{#tag:nowiki|some text}}
frame:callParserFunction{ name = '#tag', args = { 'nowiki', 'some text' } }
frame:callParserFunction( '#tag', { 'nowiki', 'some text' } )
frame:callParserFunction( '#tag', 'nowiki', 'some text' )
frame:callParserFunction( '#tag:nowiki', 'some text' )

-- {{#tag:ref|some text|name=foo|group=bar}}
frame:callParserFunction{ name = '#tag:ref', args = {
    'some text', name = 'foo', group = 'bar'
} }

Notare che, come con frame:expandTemplate(), il nome della funzione e gli argomenti non vengono processati prima di essere passati alla funzione parser.

frame:expandTemplate

frame:expandTemplate{ title = title, args = table }

Notare l'uso di named arguments.

Si tratta di inclusione. La chiamata

frame:expandTemplate{ title = 'template', args = { 'arg1', 'arg2', name = 'arg3' } }

fa più o meno la stessa cosa da Lua che {{template|arg1|arg2|name=arg3}} fa in wikitext. Come in transclusion, se il titolo passato non contiene un prefisso namespace si supporrà essere nel Template: namespace.
[does roughly the same thing from Lua that <code>{{template|arg1|arg2|name=arg3}}</code> does in wikitext. As in transclusion, if the passed title does not contain a namespace prefix it will be assumed to be in the Template: namespace.]

Si noti che il titolo e gli argomenti non vengono processati prima di essere passati nel template:

-- Questo è più o meno equivalente in wikitext come
--  {{template|{{!}}}}
frame:expandTemplate{ title = 'template', args = { '|' } }

-- Questo è più o meno equivalente in wikitext come
--  {{template|{{((}}!{{))}}}}
frame:expandTemplate{ title = 'template', args = { '{{!}}' } }

frame:extensionTag

frame:extensionTag( name, content, args )
frame:extensionTag{ name = string, content = string, args = table_or_string }

Questo è equivalente alla chiamata frame:callParserFunction() con nome funzione '#tag:' .. name e con content prepended to args.

-- Queste sono equivalenti
frame:extensionTag{ name = 'ref', content = 'some text', args = { name = 'foo', group = 'bar' } }
frame:extensionTag( 'ref', 'some text', { name = 'foo', group = 'bar' } )

frame:callParserFunction{ name = '#tag:ref', args = {
    'some text', name = 'foo', group = 'bar'
} }
-- Queste sono equivalenti
frame:extensionTag{ name = 'ref', content = 'some text', args = 'some other text' }
frame:callParserFunction{ name = '#tag:ref', args = {
    'some text', 'some other text'
} }

frame:getParent

frame:getParent()

La chiamata sul frame creato da {{#invoke:}}, restituisce la struttura (frame) per la pagina che ha richiamato {{#invoke:}}. La chiamata su quel frame, restituisce nil.

frame:getTitle

frame:getTitle()

Restituisce il titolo associato al frame come stringa. Per il frame creato da {{#invoke:}}, questo è il titolo del modulo richiamato.

frame:newChild

frame:newChild{ title = title, args = table }

Notare l'utilizzo di named arguments.

Crea un nuovo Frame object che è un figlio del frame corrente, con argomenti e titolo opzionali.

Questo è destinato principalmente per l'utilizzo nella console di debug per le funzioni che normalmente sarebbero chiamate da {{#invoke:}}. Il numero di frame che può essere creato in qualsiasi momento è limitato.

frame:preprocess

frame:preprocess( string )
frame:preprocess{ text = string }

Questo espande wikitext nel contesto del frame, cioè i template, le funzioni parser e i parametri quali {{{1}}} sono espansi.

Alcuni tag speciali scritti in notazione di tipo XML, come ad esempio <pre>, <nowiki>, <gallery> e <ref>, verranno sostituiti con ""strip markers"; stringhe speciali che iniziano con un carattere di delete(ASCII 127), possono essere sostituiti con HTML dopo che sono stati restituiti da #invoke.

Se si sta espandendo un unico template, utilizzare frame:expandTemplate invece di cercare di costruire una stringa wikitext e passare a questo metodo. È più veloce e meno incline a errori se gli argomenti contengono caratteri pipe (|) o altri wikimarkup.

frame:getArgument

frame:getArgument( arg )
frame:getArgument{ name = arg }

Ottiene un oggetto per l'argomento specificato, o nil se non viene fornito l'argomento.

L'oggetto restituito è un metodo, object:expand(), che restituisce il wikitext ampliato per l'argomento.

frame:newParserValue

frame:newParserValue( text )
frame:newParserValue{ text = text }

Restituisce un oggetto con un metodo, object:expand(), che restituisce il risultato di frame:preprocess( text ).

frame:newTemplateParserValue

frame:newTemplateParserValue{ title = title, args = table }

Notare l'utilizzo di named arguments.

Restituisce un oggetto con un metodo, object:expand(), che restituisce il risultato di frame:expandTemplate richiamato con gli argomenti dati.

frame:argumentPairs

frame:argumentPairs() Uguale a pairs( frame.args ). Incluso per la compatibilità all'indietro.

HTML library

mw.html è un'interfaccia fluida per la costruzione di complessi HTML da Lua. Un oggetto mw.html può essere creato utilizzando mw.html.create.

Funzioni documentate come mw.html.name sono disponibili sulla tabella globale mw.html; funzioni documentate come mw.html:name sono metodi di un oggetto mw.html (vedi mw.html.create).

Un esempio di base potrebbe essere il seguente:

local div = mw.html.create( 'div' )
div
attr( 'id', 'testdiv' )
css( 'width', '100%' )
wikitext( 'Some text' )
tag( 'hr' )
return tostring( div )
-- Output: <div id="testdiv" style="width:100%;">Some text<hr /></div>

mw.html.create

mw.html.create( tagName, args )

Crea un nuovo oggetto mw.html contenente un elemento HTML tagName. È inoltre possibile passare una stringa vuota o nil come tagName al fine di creare un oggetto mw.html vuoto.

args può essere una tabelle con le seguenti chiavi:

  • args.selfClosing: forza il tag corrente ad essere a chiusura automatica, anche se my.html non lo riconosce come auto-chiusura
  • args.parent: padre dell'istanza mw.html corrente (destinato ad uso interno)

mw.html:node

html:node( builder )

Aggiunge un nodo figlio mw.html (builder) all'istanza mw.html corrente. Se viene passato un parametro nil, questo è un no-op[11]

mw.html:wikitext

html:wikitext( ... )

Aggiunge un numero indeterminato di stringhe wikitext all'oggetto mw.html.

Notare che si ferma al primo elemento nil.

mw.html:newline

html:newline()

Aggiunge una nuova linea all'oggetto mw.html.

mw.html:tag

html:tag( tagName, args )

Aggiunge un nuovo nodo figlio con il tagName dato al costruttore, e restituisce un'istanza mw.html che rappresenta quel nuovo nodo. Il parametro args è identico a quello di mw.html.create.

mw.html:attr

html:attr( name, value )
html:attr( table )

Imposta un attributo HTML con il name e value dato sul nodo. Alternatively a table holding name->value pairs of attributes to set can be passed. Nella prima forma, un value pari a nil fa sì che qualsiasi attributo con il nome dato sarà disimpostato se è stato precedentemente impostato.

mw.html:getAttr

html:getAttr( name )

Ottiene il valore di un attributo HTML precedentemente impostato usando html:attr() con il dato name.

mw.html:addClass

html:addClass( class )

Aggiunge un nome di classe per l'attributo di classe nodo. Se VIENE Passato un Parametro nil, Questo e un no-op[11].

mw.html:css

html:css( name, value )
html:css( table )

Imposta una proprietà CSS con il dato name e value sul nodo. In alternativa una tabella che contiene una coppianame->value di oggetti da impostare, può essere passata. Nella prima forma, un valore pari a nil fa sì che qualsiasi proprietà con il nome dato sarà disabilitato se è stato precedentemente impostato.

mw.html:cssText

html:cssText( css )

Aggiungete un raw css per attributo di stile del nodo. Se viene passato un parametro nil, questo è un no-op[11].

mw.html:done

html:done()

Restituisce il nodo padre sotto il quale è stato creato il nodo corrente. Come jQuery.end, si tratta di una funzione di convenienza per permettere la costruzione di diversi nodi figlio per essere concatenati in una singola istruzione.

mw.html:allDone

html:allDone()

Like html:done(), but traverses all the way to the root node of the tree and returns it.

Language library

I codici di lingua sono descritti in Language code. Molti dei codici di lingua MediaWiki sono simili al codice di lingua IETF, ma non tutti i codici di lingua MediaWiki sono tag IETF validi o viceversa.

Funzioni documentate come mw.language.name sono disponibili sulla tabella globale mw.language; funzioni documentate come mw.language:name sono metodi di un oggetto linguaggio (vedi mw.language.new).

mw.language.fetchLanguageName

mw.language.fetchLanguageName( code, inLanguage )

Il nome completo del linguaggio per il codice della lingua data: nome nativo (linguaggio autonimoa[12] - language autonym) per impostazione predefinita, nome tradotto nella lingua di destinazione se un valore è dato per inLanguage.

mw.language.fetchLanguageNames

mw.language.fetchLanguageNames()
mw.language.fetchLanguageNames( inLanguage )
mw.language.fetchLanguageNames( inLanguage, include )

Recupera l'elenco delle lingue conosciute per MediaWiki, restituendo un codice di mappatura tabella al nome della lingua.

Per impostazione predefinita il nome restituito è l'opposto di lingua; passando un codice di lingua per inLanguage restituisce tutti i nomi in quella lingua.

Per impostazione predefinita, solo i nomi delle lingue conosciute per MediaWiki vengono restituiti; passando 'all' per include restituirà tutte le lingue disponibili (ad esempio da Extension:CLDR), mentre passando 'mwfile' includerà solo le lingue con messaggi personalizzati inclusi in MediaWiki o estensioni abilitate. Per selezionare in modo esplicito l'impostazione predefinita, 'mw' può essere passato.

mw.language.getContentLanguage

mw.language.getContentLanguage()
mw.getContentLanguage()

Restituisce un nuovo oggetto linguaggio per il linguaggio predefinito contenuto di wiki.

mw.language.getFallbacksFor

mw.language.getFallbacksFor( code )

Restituisce un elenco di codici di lingua MediaWiki alternativi per il codice specificato.

mw.language.isKnownLanguageTag

mw.language.isKnownLanguageTag( code )

Restituisce true se un codice di linguaggio è noto per MediaWiki.

Un codice di lingua è "conosciuto" ("know"), se si tratta di un "codice valido incorporato" ("valid built-in code" - vale a dire che restituisce true per mw.language.isValidBuiltInCode) e restituisce una stringa non vuota per mw.language.fetchLanguageName.

mw.language.isSupportedLanguage

mw.language.isSupportedLanguage( code )

Controlla se ogni localizzazione in MediaWiki è disponibile per tale codice di lingua.

Un codice lingua è "supportato" se si tratta di un codice "valido" (restituisce true per mw.language.isValidCode), non contiene lettere maiuscole e ha un file di messaggi nella versione attualmente in esecuzione di MediaWiki.

È possibile per un codice lingua essere "supportato" (supported), ma non "conosciuto" ("know" - vale a dire che restituisce true per mw.language.isKnownLanguageTag). Si noti inoltre che alcuni codici sono "supportati" ("supported"), nonostante mw.language.isValidBuiltInCode restituisca false.

mw.language.isValidBuiltInCode

mw.language.isValidBuiltInCode( code )

Restituisce true se un codice di lingua è una forma valida ai fini della personalizzazione interna di MediaWiki.

Il codice non può effettivamente corrispondere ad alcuna lingua conosciuta.

Un codice di lingua è un "codice valido incorporato" ("valid built-in code"), se si tratta di un codice "valido" ("valid" - vale a dire che restituisce true per mw.language.isValidCode); si compone di solo lettere ASCII, numeri e trattini; ed è lungo almeno due caratteri.

Si noti che alcuni codici sono "supportati" ("supportede" - vale a dire che restituiscono true dal mw.language.isSupportedLanguage), anche se questa funzione restituisce false.

mw.language.isValidCode

mw.language.isValidCode( code )

Restituisce true se una stringa di codice lingua è una forma valida, anche se non esiste. Questo include i codici che vengono utilizzati esclusivamente per la personalizzazione tramite il namespace MediaWiki.

Il codice non può effettivamente corrispondere ad alcuna lingua conosciuta.

Un codice di lingua è valido se non contiene alcuni caratteri non sicuri (due punti, una o due citazioni, barre, barre rovesciate, parentesi quadre, e commerciali, o NUL ASCII) ed è comunque consentito in un titolo di pagina.

mw.language.new

mw.language.new( code )
mw.getLanguage( code )

Crea un nuovo oggetto lingua. Gli ggetti lingua non hanno alcuna proprietà accessibili al pubblico, ma hanno diversi metodi, che sono documentati qui di seguito.

Vi è un limite al numero di codici di lingua distinte che può essere utilizzato su una pagina. Il superamento di questo limite comporta errori.

mw.language:getCode

lang:getCode()

Returns the language code for this language object.

mw.language:getFallbackLanguages

lang:getFallbackLanguages()

Returns a list of MediaWiki's fallback language codes for this language object. Equivalent to mw.language.getFallbacksFor( lang:getCode() ).

mw.language:isRTL

lang:isRTL()

Returns true if the language is written right-to-left, false if it is written left-to-right.

mw.language:lc

lang:lc( s )

Converts the string to lowercase, honoring any special rules for the given language.

When the Ustring library is loaded, the mw.ustring.lower() function is implemented as a call to mw.language.getContentLanguage():lc( s ).

mw.language:lcfirst

lang:lcfirst( s )

Converts the first character of the string to lowercase, as with lang:lc().

mw.language:uc

lang:uc( s )

Converts the string to uppercase, honoring any special rules for the given language.

When the Ustring library is loaded, the mw.ustring.upper() function is implemented as a call to mw.language.getContentLanguage():uc( s ).

mw.language:ucfirst

lang:ucfirst( s )

Converts the first character of the string to uppercase, as with lang:uc().

mw.language:caseFold

lang:caseFold( s )

Converts the string to a representation appropriate for case-insensitive comparison. Note that the result may not make any sense when displayed.

mw.language:formatNum

lang:formatNum( n )

Formats a number with grouping and decimal separators appropriate for the given language. Given 123456.78, this may produce "123,456.78", "123.456,78", or even something like "١٢٣٬٤٥٦٫٧٨" depending on the language and wiki configuration.

mw.language:formatDate

lang:formatDate( format, timestamp, local )

Formats a date according to the given format string. If timestamp is omitted, the default is the current time. The value for local must be a boolean or nil; if true, the time is formatted in the wiki's local time rather than in UTC.

The format string and supported values for timestamp are identical to those for the #time parser function from Extension:ParserFunctions. Note that backslashes may need to be doubled in the Lua string where they wouldn't in wikitext:

-- This outputs a newline, where {{#time:\n}} would output a literal "n" (n)
lang:formatDate( '\n' )

-- This outputs a literal "n", where {{#time:\\n}} would output a backslash
-- followed by the month number. (\3)
lang:formatDate( '\\n' )

-- This outputs a backslash followed by the month number, where {{#time:\\\\n}}
-- would output two backslashes followed by the month number. (\\3)
lang:formatDate( '\\\\n' )

mw.language:formatDuration

lang:formatDuration( seconds )
lang:formatDuration( seconds, allowedIntervals )

Breaks a duration in seconds into more human-readable units, e.g. 12345 to 3 hours, 25 minutes and 45 seconds, returning the result as a string.

allowedIntervals, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'weeks', 'days', 'hours', 'minutes', and 'seconds'.

mw.language:parseFormattedNumber

lang:parseFormattedNumber( s )

This takes a number as formatted by lang:formatNum() and returns the actual number. In other words, this is basically a language-aware version of tonumber().

mw.language:convertPlural

lang:convertPlural( n, ... )
lang:convertPlural( n, forms )
lang:plural( n, ... )
lang:plural( n, forms )

This chooses the appropriate grammatical form from forms (which must be a sequence table) or ... based on the number n. For example, in English you might use n .. ' ' .. lang:plural( n, 'sock', 'socks' ) or n .. ' ' .. lang:plural( n, { 'sock', 'socks' } ) to generate grammatically-correct text whether there is only 1 sock or 200 socks.

The necessary values for the sequence are language-dependent, see Help:Magic words#Localization and translatewiki:FAQ#PLURAL for some details.

mw.language:convertGrammar

lang:convertGrammar( word, case )
lang:grammar( case, word )

Note the different parameter order between the two aliases. convertGrammar matches the order of the method of the same name on MediaWiki's Language object, while grammar matches the order of the parser function of the same name, documented at Help:Magic words#Localisation.

This chooses the appropriate inflected form of word for the given inflection code case.

The possible values for word and case are language-dependent, see Help:Magic words#Language-dependent word conversions and translatewiki:Grammar for some details.

mw.language:gender

lang:gender( what, masculine, feminine, neutral )
lang:gender( what, { masculine, feminine, neutral } )

Chooses the string corresponding to the gender of what, which may be "male", "female", or a registered user name.

mw.language:getArrow

lang:getArrow( direction )

Returns a Unicode arrow character corresponding to direction:

  • forwards: Either "→" or "←" depending on the directionality of the language.
  • backwards: Either "←" or "→" depending on the directionality of the language.
  • left: "←"
  • right: "→"
  • up: "↑"
  • down: "↓"

mw.language:getDir

lang:getDir()

Returns "ltr" or "rtl", depending on the directionality of the language.

mw.language:getDirMark

lang:getDirMark( opposite )

Returns a string containing either U+200E (the left-to-right mark) or U+200F (the right-to-left mark), depending on the directionality of the language and whether opposite is a true or false value.

mw.language:getDirMarkEntity

lang:getDirMarkEntity( opposite )

Returns "&lrm;" or "&rlm;", depending on the directionality of the language and whether opposite is a true or false value.

mw.language:getDurationIntervals

lang:getDurationIntervals( seconds )
lang:getDurationIntervals( seconds, allowedIntervals )

Breaks a duration in seconds into more human-readable units, e.g. 12345 to 3 hours, 25 minutes and 45 seconds, returning the result as a table mapping unit names to numbers.

allowedIntervals, if given, is a table with values naming the interval units to use in the response. These include 'millennia', 'centuries', 'decades', 'years', 'days', 'hours', 'minutes', and 'seconds'.

Message library

This library is an interface to the localisation messages and the MediaWiki: namespace.

Functions documented as mw.message.name are available on the global mw.message table; functions documented as mw.message:name are methods of a message object (see mw.message.new).

mw.message.new

mw.message.new( key, ... )

Creates a new message object for the given message key.

The message object has no properties, but has several methods documented below.

mw.message.newFallbackSequence

mw.message.newFallbackSequence( ... )

Creates a new message object for the given messages (the first one that exists will be used).

The message object has no properties, but has several methods documented below.

mw.message.newRawMessage

mw.message.newRawMessage( msg, ... )

Creates a new message object, using the given text directly rather than looking up an internationalized message. The remaining parameters are passed to the new object's params() method.

The message object has no properties, but has several methods documented below.

mw.message.rawParam

mw.message.rawParam( value )

Wraps the value so that it will not be parsed as wikitext by msg:parse().

mw.message.numParam

mw.message.numParam( value )

Wraps the value so that it will automatically be formatted as by lang:formatNum(). Note this does not depend on the Language library actually being available.

mw.message.getDefaultLanguage

mw.message.getDefaultLanguage()

Returns a Language object for the default language.

mw.message:params

msg:params( ... )
msg:params( params )

Add parameters to the message, which may be passed as individual arguments or as a sequence table. Parameters must be numbers, strings, or the special values returned by mw.message.numParam() or mw.message.rawParam(). If a sequence table is used, parameters must be directly present in the table; references using the __index metamethod will not work.

Returns the msg object, to allow for call chaining.

mw.message:rawParams

msg:rawParams( ... )
msg:rawParams( params )

Like :params(), but has the effect of passing all the parameters through mw.message.rawParam() first.

Returns the msg object, to allow for call chaining.

mw.message:numParams

msg:numParams( ... )
msg:numParams( params )

Like :params(), but has the effect of passing all the parameters through mw.message.numParam() first.

Returns the msg object, to allow for call chaining.

mw.message:inLanguage

msg:inLanguage( lang )

Specifies the language to use when processing the message. lang may be a string or a table with a getCode() method (i.e. a Language object).

The default language is the one returned by mw.message.getDefaultLanguage().

Returns the msg object, to allow for call chaining.

mw.message:useDatabase

msg:useDatabase( bool )

Specifies whether to look up messages in the MediaWiki: namespace (i.e. look in the database), or just use the default messages distributed with MediaWiki.

The default is true.

Returns the msg object, to allow for call chaining.

mw.message:plain

msg:plain()

Substitutes the parameters and returns the message wikitext as-is. Template calls and parser functions are intact.

mw.message:exists

msg:exists()

Returns a boolean indicating whether the message key exists.

mw.message:isBlank

msg:isBlank()

Returns a boolean indicating whether the message key has content. Returns true if the message key does not exist or the message is the empty string.

mw.message:isDisabled

msg:isDisabled()

Returns a boolean indicating whether the message key is disabled. Returns true if the message key does not exist or if the message is the empty string or the string "-".

Site library

mw.site.currentVersion

A string holding the current version of MediaWiki.

mw.site.scriptPath

The value of $wgScriptPath.

mw.site.server

The value of $wgServer.

mw.site.siteName

The value of $wgSitename.

mw.site.stylePath

The value of $wgStylePath.

mw.site.namespaces

Table holding data for all namespaces, indexed by number.

The data available is:

  • id: Namespace number.
  • name: Local namespace name.
  • canonicalName: Canonical namespace name.
  • displayName: Set on namespace 0, the name to be used for display (since the name is often the empty string).
  • hasSubpages: Whether subpages are enabled for the namespace.
  • hasGenderDistinction: Whether the namespace has different aliases for different genders.
  • isCapitalized: Whether the first letter of pages in the namespace is capitalized.
  • isContent: Whether this is a content namespace.
  • isIncludable: Whether pages in the namespace can be transcluded.
  • isMovable: Whether pages in the namespace can be moved.
  • isSubject: Whether this is a subject namespace.
  • isTalk: Whether this is a talk namespace.
  • defaultContentModel: The default content model for the namespace, as a string.
  • aliases: List of aliases for the namespace.
  • subject: Reference to the corresponding subject namespace's data.
  • talk: Reference to the corresponding talk namespace's data.
  • associated: Reference to the associated namespace's data.

A metatable is also set that allows for looking up namespaces by name (localized or canonical). For example, both mw.site.namespaces[4] and mw.site.namespaces.Project will return information about the Project namespace.

mw.site.contentNamespaces

Table holding just the content namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.subjectNamespaces

Table holding just the subject namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.talkNamespaces

Table holding just the talk namespaces, indexed by number. See mw.site.namespaces for details.

mw.site.stats

Table holding site statistics. Available statistics are:

  • pages: Number of pages in the wiki.
  • articles: Number of articles in the wiki.
  • files: Number of files in the wiki.
  • edits: Number of edits in the wiki.
  • views: Number of views in the wiki. Not available if $wgDisableCounters is set.
  • users: Number of users in the wiki.
  • activeUsers: Number of active users in the wiki.
  • admins: Number of users in group 'sysop' in the wiki.

mw.site.stats.pagesInCategory

mw.site.stats.pagesInCategory( category, which )

This function is expensive

Gets statistics about the category. If which is unspecified, nil, or "*", returns a table with the following properties:

  • all: Total pages, files, and subcategories.
  • subcats: Number of subcategories.
  • files: Number of files.
  • pages: Number of pages.

If which is one of the above keys, just the corresponding value is returned instead.

Each new category queried will increment the expensive function count.

mw.site.stats.pagesInNamespace

mw.site.stats.pagesInNamespace( ns )

Returns the number of pages in the given namespace (specify by number).

mw.site.stats.usersInGroup

mw.site.stats.usersInGroup( group )

Returns the number of users in the given group.

mw.site.interwikiMap

mw.site.interwikiMap( filter )

Returns a table holding data about available interwiki prefixes. If filter is the string "local", then only data for local interwiki prefixes is returned. If filter is the string "!local", then only data for non-local prefixes is returned. If no filter is specified, data for all prefixes is returned. A "local" prefix in this context is one that is for the same project. For example, on the English Wikipedia, other-language Wikipedias are considered local, while Wiktionary and such are not.

Keys in the table returned by this function are interwiki prefixes, and the values are subtables with the following properties:

  • prefix - the interwiki prefix.
  • url - the URL that the interwiki points to. The page name is represented by the parameter $1.
  • isProtocolRelative - a boolean showing whether the URL is protocol-relative.
  • isLocal - whether the URL is for a site in the current project.
  • isCurrentWiki - whether the URL is for the current wiki.
  • isTranscludable - whether pages using this interwiki prefix are transcludable. This requires scary transclusion, which is disabled on Wikimedia wikis.
  • isExtraLanguageLink - whether the interwiki is listed in $wgExtraInterlanguageLinkPrefixes.
  • displayText - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the display text shown for the interlanguage link. Nil if not specified.
  • tooltip - for links listed in $wgExtraInterlanguageLinkPrefixes, this is the tooltip text shown when users hover over the interlanguage link. Nil if not specified.

Text library

The text library provides some common text processing functions missing from the String library and the Ustring library. These functions are safe for use with UTF-8 strings.

mw.text.decode

mw.text.decode( s )
mw.text.decode( s, decodeNamedEntities )

Replaces HTML entities in the string with the corresponding characters.

If decodeNamedEntities is omitted or false, the only named entities recognized are '&lt;', '&gt;', '&amp;', '&quot;', and '&nbsp;'. Otherwise, the list of HTML5 named entities to recognize is loaded from PHP's get_html_translation_table function.

mw.text.encode

mw.text.encode( s )
mw.text.encode( s, charset )

Replaces characters in a string with HTML entities. Characters '<', '>', '&', '"', and the non-breaking space are replaced with the appropriate named entities; all others are replaced with numeric entities.

If charset is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in [set]. The default charset is '<>&"\' ' (the space at the end is the non-breaking space, U+00A0).

mw.text.jsonDecode

mw.text.jsonDecode( s )
mw.text.jsonDecode( s, flags )

Decodes a JSON string. flags is 0 or a combination (use +) of the flags mw.text.JSON_PRESERVE_KEYS and mw.text.JSON_TRY_FIXING.

Normally JSON's zero-based arrays are renumbered to Lua one-based sequence tables; to prevent this, pass mw.text.JSON_PRESERVE_KEYS.

To relax certain requirements in JSON, such as no terminal comma in arrays or objects, pass mw.text.JSON_TRY_FIXING. This is not recommended.

Limitations:

  • Decoded JSON arrays may not be Lua sequences if the array contains null values.
  • JSON objects will drop keys having null values.
  • It is not possible to directly tell whether the input was a JSON array or a JSON object with sequential integer keys.
  • A JSON object having sequential integer keys beginning with 1 will decode to the same table structure as a JSON array with the same values, despite these not being at all equivalent, unless mw.text.JSON_PRESERVE_KEYS is used.

mw.text.jsonEncode

mw.text.jsonEncode( value )
mw.text.jsonEncode( value, flags )

Encode a JSON string. Errors are raised if the passed value cannot be encoded in JSON. flags is 0 or a combination (use +) of the flags mw.text.JSON_PRESERVE_KEYS and mw.text.JSON_PRETTY.

Normally Lua one-based sequence tables are encoded as JSON zero-based arrays; when mw.text.JSON_PRESERVE_KEYS is set in flags, zero-based sequence tables are encoded as JSON arrays.

Limitations:

  • Empty tables are always encoded as empty arrays ([]), not empty objects ({}).
  • Sequence tables cannot be encoded as JSON objects without adding a "dummy" element.
  • To produce objects or arrays with nil values, a tricky implementation of the __pairs metamethod is required.
  • A Lua table having sequential integer keys beginning with 0 will encode as a JSON array, the same as a Lua table having integer keys beginning with 1, unless mw.text.JSON_PRESERVE_KEYS is used.
  • When both a number and the string representation of that number are used as keys in the same table, behavior is unspecified.

mw.text.killMarkers

mw.text.killMarkers( s )

Removes all MediaWiki strip markers from a string.

mw.text.listToText

mw.text.listToText( list )
mw.text.listToText( list, separator, conjunction )

Join a list, prose-style. In other words, it's like table.concat() but with a different separator before the final item.

The default separator is taken from MediaWiki:comma-separator in the wiki's content language, and the default conjuction is MediaWiki:and concatenated with MediaWiki:word-separator.

Examples, using the default values for the messages:

-- Returns the empty string
mw.text.listToText( {} )

-- Returns "1"
mw.text.listToText( { 1 } )

-- Returns "1 and 2"
mw.text.listToText( { 1, 2 } )

-- Returns "1, 2, 3, 4 and 5"
mw.text.listToText( { 1, 2, 3, 4, 5 } )

-- Returns "1; 2; 3; 4 or 5"
mw.text.listToText( { 1, 2, 3, 4, 5 }, '; ', ' or ' )

mw.text.nowiki

mw.text.nowiki( s )

Replaces various characters in the string with HTML entities to prevent their interpretation as wikitext. This includes:

  • The following characters: '"', '&', "'", '<', '=', '>', '[', ']', '{', '|', '}'
  • The following characters at the start of the string or immediately after a newline: '#', '*', ':', ';', space, tab ('\t')
  • Blank lines will have one of the associated newline or carriage return characters escaped
  • "----" at the start of the string or immediately after a newline will have the first '-' escaped
  • "__" will have one underscore escaped
  • "://" will have the colon escaped
  • A whitespace character following "ISBN", "RFC", or "PMID" will be escaped

mw.text.split

mw.text.split( s, pattern, plain )

Splits the string into substrings at boundaries matching the Ustring pattern pattern. If plain is specified and true, pattern will be interpreted as a literal string rather than as a Lua pattern (just as with the parameter of the same name for mw.ustring.find()). Returns a table containing the substrings.

For example, mw.text.split( 'a b\tc\nd', '%s' ) would return a table { 'a', 'b', 'c', 'd' }.

If pattern matches the empty string, s will be split into individual characters.

mw.text.gsplit

mw.text.gsplit( s, pattern, plain )

Returns an iterator function that will iterate over the substrings that would be returned by the equivalent call to mw.text.split().

mw.text.tag

mw.text.tag( name, attrs, content )
mw.text.tag{ name = string, attrs = table, content = string|false }

Note the use of named arguments.

Generates an HTML-style tag for name.

If attrs is given, it must be a table with string keys. String and number values are used as the value of the attribute; boolean true results in the key being output as an HTML5 valueless parameter; boolean false skips the key entirely; and anything else is an error.

If content is not given (or is nil), only the opening tag is returned. If content is boolean false, a self-closed tag is returned. Otherwise it must be a string or number, in which case that content is enclosed in the constructed opening and closing tag. Note the content is not automatically HTML-encoded; use mw.text.encode() if needed.

For properly returning extension tags such as <ref>, use frame:extensionTag() instead.

mw.text.trim

mw.text.trim( s )
mw.text.trim( s, charset )

Remove whitespace or other characters from the beginning and end of a string.

If charset is supplied, it should be a string as appropriate to go inside brackets in a Ustring pattern, i.e. the "set" in [set]. The default charset is ASCII whitespace, "%t%r%n%f ".

mw.text.truncate

mw.text.truncate( text, length )
mw.text.truncate( text, length, ellipsis )
mw.text.truncate( text, length, ellipsis, adjustLength )

Truncates text to the specified length, adding ellipsis if truncation was performed. If length is positive, the end of the string will be truncated; if negative, the beginning will be removed. If adjustLength is given and true, the resulting string including ellipsis will not be longer than the specified length.

The default value for ellipsis is taken from MediaWiki:ellipsis in the wiki's content language.

Examples, using the default "..." ellipsis:

-- Returns "foobarbaz"
mw.text.truncate( "foobarbaz", 9 )

-- Returns "fooba..."
mw.text.truncate( "foobarbaz", 5 )

-- Returns "...arbaz"
mw.text.truncate( "foobarbaz", -5 )

-- Returns "foo..."
mw.text.truncate( "foobarbaz", 6, nil, true )

-- Returns "foobarbaz", because that's shorter than "foobarba..."
mw.text.truncate( "foobarbaz", 8 )

mw.text.unstripNoWiki

mw.text.unstripNoWiki( s )

Replaces MediaWiki <nowiki> strip markers with the corresponding text. Other types of strip markers are not changed.

mw.text.unstrip

mw.text.unstrip( s )

Equivalent to mw.text.killMarkers( mw.text.unstripNoWiki( s ) ).

This no longer reveals the HTML behind special page transclusion, <ref> tags, and so on as it did in earlier versions of Scribunto.

Title library

mw.title.equals

mw.title.equals( a, b )

Test for whether two titles are equal. Note that fragments are ignored in the comparison.

mw.title.compare

mw.title.compare( a, b )

Returns -1, 0, or 1 to indicate whether the title a is less than, equal to, or greater than title b

mw.title.getCurrentTitle

mw.title.getCurrentTitle()

Returns the title object for the current page.

mw.title.new

mw.title.new( text, namespace )
mw.title.new( id )

This function is expensive when called with an ID

Creates a new title object.

If a number id is given, an object is created for the title with that page_id. The title referenced will be counted as linked from the current page. If the page_id does not exist, returns nil. The expensive function count will be incremented if the title object created is not for a title that has already been loaded.

If a string text is given instead, an object is created for that title (even if the page does not exist). If the text string does not specify a namespace, namespace (which may be any key found in mw.site.namespaces) will be used. If the text is not a valid title, nil is returned.

mw.title.makeTitle

mw.title.makeTitle( namespace, title, fragment, interwiki )

Creates a title object with title title in namespace namespace, optionally with the specified fragment and interwiki prefix. namespace may be any key found in mw.site.namespaces. If the resulting title is not valid, returns nil.

Note that mw.title.new( 'Module:Foo', 'Template' ) will create an object for the page Module:Foo, while mw.title.makeTitle( 'Template', 'Module:Foo' ) will create an object for the page Template:Module:Foo.

Title objects

A title object has a number of properties and methods. Most of the properties are read-only.

Note that fields ending with text return titles as string values whereas the fields ending with title return title objects.

  • id: The page_id. 0 if the page does not exist. This may be expensive, and the page will be recorded as a link.
  • interwiki: The interwiki prefix, or the empty string if none.
  • namespace: The namespace number.
  • fragment: The fragment, or the empty string. May be assigned.
  • nsText: The text of the namespace for the page.
  • subjectNsText: The text of the subject namespace for the page.
  • text: The title of the page, without the namespace or interwiki prefixes.
  • prefixedText: The title of the page, with the namespace and interwiki prefixes.
  • fullText: The title of the page, with the namespace and interwiki prefixes and the fragment.
  • rootText: If this is a subpage, the title of the root page without prefixes. Otherwise, the same as title.text.
  • baseText: If this is a subpage, the title of the page it is a subpage of without prefixes. Otherwise, the same as title.text.
  • subpageText: If this is a subpage, just the subpage name. Otherwise, the same as title.text.
  • canTalk: Whether the page for this title could have a talk page.
  • exists: Whether the page exists. Alias for file.exists for Media-namespace titles. For File-namespace titles this checks the existence of the file description page, not the file itself. This may be expensive, and the page will be recorded as a link.
  • file, fileExists: See #File metadata below.
  • isContentPage: Whether this title is in a content namespace.
  • isExternal: Whether this title has an interwiki prefix.
  • isLocal: Whether this title is in this project. For example, on the English Wikipedia, any other Wikipedia is considered "local" while Wiktionary and such are not.
  • isRedirect: Whether this is the title for a page that is a redirect. This may be expensive, and the page will be recorded as a link.
  • isSpecialPage: Whether this is the title for a possible special page (i.e. a page in the Special: namespace).
  • isSubpage: Whether this title is a subpage of some other title.
  • isTalkPage: Whether this is a title for a talk page.
  • isSubpageOf( title2 ): Whether this title is a subpage of the given title.
  • inNamespace( ns ): Whether this title is in the given namespace. Namespaces may be specified by anything that is a key found in mw.site.namespaces.
  • inNamespaces( ... ): Whether this title is in any of the given namespaces. Namespaces may be specified by anything that is a key found in mw.site.namespaces.
  • hasSubjectNamespace( ns ): Whether this title's subject namespace is in the given namespace. Namespaces may be specified by anything that is a key found in mw.site.namespaces.
  • contentModel: The content model for this title, as a string. This may be expensive, and the page will be recorded as a link.
  • basePageTitle: The same as mw.title.makeTitle( title.namespace, title.baseText ).
  • rootPageTitle: The same as mw.title.makeTitle( title.namespace, title.rootText ).
  • talkPageTitle: The same as mw.title.makeTitle( mw.site.namespaces[title.namespace].talk.id, title.text ), or nil if this title cannot have a talk page.
  • subjectPageTitle: The same as mw.title.makeTitle( mw.site.namespaces[title.namespace].subject.id, title.text ).
  • protectionLevels: The page's protection levels. This is a table with keys corresponding to each action (e.g., "edit" and "move"). The table values are arrays, the first item of which is a string containing the protection level. If the page is unprotected, either the table values or the array items will be nil. This is expensive.
  • subPageTitle( text ): The same as mw.title.makeTitle( title.namespace, title.text .. '/' .. text ).
  • partialUrl(): Returns title.text encoded as it would be in a URL.
  • fullUrl( query, proto ): Returns the full URL (with optional query table/string) for this title. proto may be specified to control the scheme of the resulting url: "http", "https", "relative" (the default), or "canonical".
  • localUrl( query ): Returns the local URL (with optional query table/string) for this title.
  • canonicalUrl( query ): Returns the canonical URL (with optional query table/string) for this title.
  • getContent(): Returns the (unparsed) content of the page, or nil if there is no page. The page will be recorded as a transclusion.

Title objects may be compared using Relational operators. tostring( title ) will return title.prefixedText.

File metadata

Title objects representing a page in the File or Media namespace will have a property called file. This is expensive. This is a table, structured as follows:

  • exists: Whether the file exists. It will be recorded as an image usage. The fileExists property on a Title object exists for backwards compatibility reasons and is an alias for this property. If this is false, all other file properties will be nil.
  • width: The width of the file. If the file contains multiple pages, this is the width of the first page.
  • height: The height of the file. If the file contains multiple pages, this is the height of the first page.
  • pages: If the file format supports multiple pages, this is a table containing tables for each page of the file; otherwise, it is nil. The # operator can be used to get the number of pages in the file. Each individual page table contains a width and height property.
  • size: The size of the file in bytes.
  • mimeType: The MIME type of the file.
Expensive properties

The properties id, isRedirect, exists, and contentModel require fetching data about the title from the database. For this reason, the expensive function count is incremented the first time one of them is accessed for a page other than the current page. Subsequent accesses of any of these properties for that page will not increment the expensive function count again.

Other properties marked as expensive will always increment the expensive function count the first time they are accessed for a page other than the current page.

URI library

mw.uri.encode

mw.uri.encode( s, enctype )

Percent-encodes the string. The default type, "QUERY", encodes spaces using '+' for use in query strings; "PATH" encodes spaces as %20; and "WIKI" encodes spaces as '_'.

Note that the "WIKI" format is not entirely reversible, as both spaces and underscores are encoded as '_'.

mw.uri.decode

mw.uri.decode( s, enctype )

Percent-decodes the string. The default type, "QUERY", decodes '+' to space; "PATH" does not perform any extra decoding; and "WIKI" decodes '_' to space.

mw.uri.anchorEncode

mw.uri.anchorEncode( s )

Encodes a string for use in a MediaWiki URI fragment.

mw.uri.buildQueryString

mw.uri.buildQueryString( table )

Encodes a table as a URI query string. Keys should be strings; values may be strings or numbers, sequence tables, or boolean false.

mw.uri.parseQueryString

mw.uri.parseQueryString( s, i, j )

Decodes the query string s to a table. Keys in the string without values will have a value of false; keys repeated multiple times will have sequence tables as values; and others will have strings as values.

The optional numerical arguments i and j can be used to specify a substring of s to be parsed, rather than the entire string. i is the position of the first character of the substring, and defaults to 1. j is the position of the last character of the substring, and defaults to the length of the string. Both i and j can be negative, as in string.sub.

mw.uri.canonicalUrl

mw.uri.canonicalUrl( page, query )

Returns a URI object for the canonical URL for a page, with optional query string/table.

mw.uri.fullUrl

mw.uri.fullUrl( page, query )

Returns a URI object for the full URL for a page, with optional query string/table.

mw.uri.localUrl

mw.uri.localUrl( page, query )

Returns a URI object for the local URL for a page, with optional query string/table.

mw.uri.new

mw.uri.new( s )

Constructs a new URI object for the passed string or table. See the description of URI objects for the possible fields for the table.

mw.uri.validate

mw.uri.validate( table )

Validates the passed table (or URI object). Returns a boolean indicating whether the table was valid, and on failure a string explaining what problems were found.

URI object

The URI object has the following fields, some or all of which may be nil:

  • protocol: String protocol/scheme
  • user: String user
  • password: String password
  • host: String host name
  • port: Integer port
  • path: String path
  • query: A table, as from mw.uri.parseQueryString
  • fragment: String fragment.

The following properties are also available:

  • userInfo: String user and password
  • hostPort: String host and port
  • authority: String user, password, host, and port
  • queryString: String version of the query table
  • relativePath: String path, query string, and fragment

tostring() will give the URI string.

Methods of the URI object are:

mw.uri:parse

uri:parse( s )

Parses a string into the current URI object. Any fields specified in the string will be replaced in the current object; fields not specified will keep their old values.

mw.uri:clone

uri:clone()

Makes a copy of the URI object.

mw.uri:extend

uri:extend( parameters )

Merges the parameters table into the object's query table.

Ustring library

The ustring library is intended to be a direct reimplementation of the standard String library, except that the methods operate on characters in UTF-8 encoded strings rather than bytes.

Most functions will raise an error if the string is not valid UTF-8; exceptions are noted.

mw.ustring.maxPatternLength

The maximum allowed length of a pattern, in bytes.

mw.ustring.maxStringLength

The maximum allowed length of a string, in bytes.

mw.ustring.byte

mw.ustring.byte( s, i, j )

Returns individual bytes; identical to string.byte().

mw.ustring.byteoffset

mw.ustring.byteoffset( s, l, i )

Returns the byte offset of a character in the string. The default for both l and i is 1. i may be negative, in which case it counts from the end of the string.

The character at l == 1 is the first character starting at or after byte i; the character at l == 0 is the first character starting at or before byte i. Note this may be the same character. Greater or lesser values of l are calculated relative to these.

mw.ustring.char

mw.ustring.char( ... )

Much like string.char(), except that the integers are Unicode codepoints[9] rather than byte values.

mw.ustring.codepoint

mw.ustring.codepoint( s, i, j )

Much like string.byte(), except that the return values are codepoints[9] and the offsets are characters rather than bytes.

mw.ustring.find

mw.ustring.find( s, pattern, init, plain )

Much like string.find(), except that the pattern is extended as described in Ustring patterns and the init offset is in characters rather than bytes.

mw.ustring.format

mw.ustring.format( format, ... )

Identical to string.format(). Widths and precisions for strings are expressed in bytes, not codepoints[9] .

mw.ustring.gcodepoint

mw.ustring.gcodepoint( s, i, j )

Returns three values for iterating over the codepoints[9] in the string. i defaults to 1, and j to -1. This is intended for use in the iterator form of for:

<source lang="lua"> for codepoint in mw.ustring.gcodepoint( s ) do -- block end </source>

mw.ustring.gmatch

mw.ustring.gmatch( s, pattern )

Much like string.gmatch(), except that the pattern is extended as described in Ustring patterns.

mw.ustring.gsub

mw.ustring.gsub( s, pattern, repl, n )

Much like string.gsub(), except that the pattern is extended as described in Ustring patterns.

mw.ustring.isutf8

mw.ustring.isutf8( s )

Returns true if the string is valid UTF-8, false if not.

mw.ustring.len

mw.ustring.len( s )

Returns the length of the string in codepoints[9] , or nil if the string is not valid UTF-8.

See string.len() for a similar function that uses byte length rather than codepoints.

mw.ustring.lower

mw.ustring.lower( s )

Much like string.lower(), except that all characters with lowercase to uppercase definitions in Unicode are converted.

If the Language library is also loaded, this will instead call lc() on the default language object.

mw.ustring.match

mw.ustring.match( s, pattern, init )

Much like string.match(), except that the pattern is extended as described in Ustring patterns and the init offset is in characters rather than bytes.

mw.ustring.rep

mw.ustring.rep( s, n )

Identical to string.rep().

mw.ustring.sub

mw.ustring.sub( s, i, j )

Much like string.sub(), except that the offsets are characters rather than bytes.

mw.ustring.toNFC

mw.ustring.toNFC( s )

Converts the string to Normalization Form C. Returns nil if the string is not valid UTF-8.

mw.ustring.toNFD

mw.ustring.toNFD( s )

Converts the string to Normalization Form D. Returns nil if the string is not valid UTF-8.

mw.ustring.upper

mw.ustring.upper( s )

Much like string.upper(), except that all characters with uppercase to lowercase definitions in Unicode are converted.

If the Language library is also loaded, this will instead call uc() on the default language object.

Ustring patterns

Patterns in the ustring functions use the same syntax as the String library patterns. The major difference is that the character classes are redefined in terms of Unicode character properties:

  • %a: represents all characters with General Category "Letter".
  • %c: represents all characters with General Category "Control".
  • %d: represents all characters with General Category "Decimal Number".
  • %l: represents all characters with General Category "Lowercase Letter".
  • %p: represents all characters with General Category "Punctuation".
  • %s: represents all characters with General Category "Separator", plus tab, linefeed, carriage return, vertical tab, and form feed.
  • %u: represents all characters with General Category "Uppercase Letter".
  • %w: represents all characters with General Category "Letter" or "Decimal Number".
  • %x: adds fullwidth character versions of the hex digits.

In all cases, characters are interpreted as Unicode characters instead of bytes, so ranges such as [0-9], patterns such as %b«», and quantifiers applied to multibyte characters will work correctly. Empty captures will capture the position in code points rather than bytes.

Loadable libraries

These libraries are not included by default, but if needed may be loaded using require().

bit32

This emulation of the Lua 5.2 bit32 library may be loaded using

bit32 = require( 'bit32' )

The bit32 library provides bitwise operations on unsigned 32-bit integers. Input numbers are truncated to integers (in an unspecified manner) and reduced modulo 232 so the value is in the range 0 to 232−1; return values are also in this range.

When bits are numbered (as in bit32.extract()), 0 is the least-significant bit (the one with value 20) and 31 is the most-significant (the one with value 231).

bit32.band

bit32.band( ... )

Returns the bitwise AND of its arguments: the result has a bit set only if that bit is set in all of the arguments.

If given zero arguments, the result has all bits set.

bit32.bnot

bit32.bnot( x )

Returns the bitwise complement of x.

bit32.bor

bit32.bor( ... )

Returns the bitwise OR of its arguments: the result has a bit set if that bit is set in any of the arguments.

If given zero arguments, the result has all bits clear.

bit32.btest

bit32.btest( ... )

Equivalent to bit32.band( ... ) ~= 0

bit32.bxor

bit32.bxor( ... )

Returns the bitwise XOR of its arguments: the result has a bit set if that bit is set in an odd number of the arguments.

If given zero arguments, the result has all bits clear.

bit32.extract

bit32.extract( n, field, width )

Extracts width bits from n, starting with bit field. Accessing bits outside of the range 0 to 31 is an error.

If not specified, the default for width is 1.

bit32.replace

bit32.replace( n, v, field, width )

Replaces width bits in n, starting with bit field, with the low width bits from v. Accessing bits outside of the range 0 to 31 is an error.

If not specified, the default for width is 1.

bit32.lshift

bit32.lshift( n, disp )

Returns the number n shifted disp bits to the left. This is a logical shift: inserted bits are 0. This is generally equivalent to multiplying by 2disp.

Note that a displacement over 31 will result in 0.

bit32.rshift

bit32.rshift( n, disp )

Returns the number n shifted disp bits to the right. This is a logical shift: inserted bits are 0. This is generally equivalent to dividing by 2disp.

Note that a displacement over 31 will result in 0.

bit32.arshift

bit32.arshift( n, disp )

Returns the number n shifted disp bits to the right. This is an arithmetic shift: if disp is positive, the inserted bits will be the same as bit 31 in the original number.

Note that a displacement over 31 will result in 0 or 4294967295.

bit32.lrotate

bit32.lrotate( n, disp )

Returns the number n rotated disp bits to the left.

Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.

bit32.rrotate

bit32.rrotate( n, disp )

Returns the number n rotated disp bits to the right.

Note that rotations are equivalent modulo 32: a rotation of 32 is the same as a rotation of 0, 33 is the same as 1, and so on.

libraryUtil

This library contains methods useful when implementing Scribunto libraries. It may be loaded using

libraryUtil = require( 'libraryUtil' )

libraryUtil.checkType

libraryUtil.checkType( name, argIdx, arg, expectType, nilOk )

Raises an error if type( arg ) does not match expectType. In addition, no error will be raised if arg is nil and nilOk is true.

name is the name of the calling function, and argIdx is the position of the argument in the argument list. These are used in formatting the error message.

libraryUtil.checkTypeMulti

libraryUtil.checkTypeMulti( name, argIdx, arg, expectTypes )

Raises an error if type( arg ) does not match any of the strings in the array expectTypes.

This is for arguments that have more than one valid type.

libraryUtil.checkTypeForIndex

libraryUtil.checkTypeForIndex( index, value, expectType )

Raises an error if type( value ) does not match expectType.

This is intended for use in implementing a __newindex metamethod.

libraryUtil.checkTypeForNamedArg

libraryUtil.checkTypeForNamedArg( name, argName, arg, expectType, nilOk )

Raises an error if type( arg ) does not match expectType. In addition, no error will be raised if arg is nil and nilOk is true.

This is intended to be used as an equivalent to libraryUtil.checkType() in methods called using Lua's "named argument" syntax, func{ name = value }.

libraryUtil.makeCheckSelfFunction

libraryUtil.makeCheckSelfFunction( libraryName, varName, selfObj, selfObjDesc )

This is intended for use in implementing "methods" on object tables that are intended to be called with the obj:method() syntax. It returns a function that should be called at the top of these methods with the self argument and the method name, which will raise an error if that self object is not selfObj.

This function will generally be used in a library's constructor function, something like this:

function myLibrary.new()
    local obj = {}
    local checkSelf = libraryUtil.makeCheckSelfFunction( 'myLibrary', 'obj', obj, 'myLibrary object' )

    function obj:method()
        checkSelf( self, 'method' )
    end

    function obj:method2()
        checkSelf( self, 'method2' )
    end

    return obj
end

luabit

The luabit library modules "bit" and "hex" may be loaded using

bit = require( 'luabit.bit' )
hex = require( 'luabit.hex' )

Note that the bit32 library contains the same operations as "luabit.bit", and the operations in "luabit.hex" may be performed using string.format() and tonumber().

The luabit module "noki" is not available, as it is entirely useless in Scribunto. The luabit module "utf8" is also not available, as it was considered redundant to the Ustring library.

ustring

The pure-Lua backend to the Ustring library may be loaded using

ustring = require( 'ustring' )

In all cases the Ustring library (mw.ustring) should be used instead, as that replaces many of the slower and more memory-intensive operations with callbacks into PHP code.

Extension libraries (mw.ext)

The following MediaWiki extensions provide additional Scribunto libraries:

See also the lists of extensions using the ScribuntoExternalLibraries and ScribuntoExternalLibraryPaths hooks.

Planned Scribunto libraries

These libraries are planned, or are in Gerrit pending review.

(none at this time)

Differences from standard Lua

Changed functions

Le seguenti funzioni sono state modificate:

setfenv()
getfenv()
potrebbe non essere disponibile, a seconda della configurazione. Se disponibile, i tentativi di accedere agli ambienti padri verranno a mancare.
getmetatable()
funziona su tabelle solo per impedire l'accesso non autorizzato ad ambienti padre.
tostring()
indirizzi puntatori delle tabelle e delle funzioni non sono disponibili. Questo per rendere la vulnerabilità di corruzione della memoria più difficile da sfruttare.
pairs()
ipairs()
è stato aggiunto il supporto per le __pairs e le __ipairs metamethods (aggiunto in Lua 5.2).
pcall()
xpcall()
certi errori interni non possono essere intercettati.
require()
può recuperare alcuni moduli built-in distribuiti con Scribunto, così come i moduli presenti nel namespace del modulo del wiki. Per recuperare i moduli wiki, utilizzare il nome della pagina completo, compreso lo spazio dei nomi. Non è possibile altrimenti accedere al filesystem locale.

Removed functions and packages

I seguenti pacchetti sono in gran parte rimossi. Solo le funzioni elencate sono disponibili:

package.*
il filesystem e l'accesso alla libreria C è stato rimosso. le funzioni e le tabelle disponibili sono:
package.loaded
package.preload
package.loaders
i caricatori che accedono alle librerie del locale filesystem o alle librerie C non sono presenti. Viene aggiunto un caricatore per le pagine Module-namespace.
package.seeall()
os.*
qui ci sono alcune funzioni non sicure, come os.execute (), che non possono essere consentite. Le funzioni disponibili sono:
os.clock()
os.date()
os.difftime()
os.time()
debug.*
la maggior parte delle funzioni non sono sicure. Le funzioni disponibili sono:
debug.traceback()

Le seguenti funzioni e pacchetti non sono disponibili:

collectgarbage()
module()
coroutine.*
Nessuna applicazione è nota, quindi non è stato esaminato per la sicurezza.
dofile()
loadfile()
io.*, file.*
Consente l'accesso al filesystem locale, che è insicuro.
load()
loadstring()
questi sono stati omessi per consentire l'analisi statica del codice sorgente Lua. Inoltre, usandoli permetterebbero al codice Lua di essere aggiunto direttamente alle pagine e ai template, che non è consigliabile per ragioni di utilizzo.
print()
questo era discussed on wikitech-l e si è deciso che dovrebbe essere omessa a favore dei valori restituiti, per migliorare la qualità del codice. Se necessario, mw.log() può essere usato per trasmettere informazioni alla console di debug.
string.dump()
può esporre i dati privati dall'ambienti padre.

Additional caveats

strutture dati referenziale
strutture dati circolari e strutture dati in cui lo stesso nodo può essere raggiunto da più di un percorso, non possono essere inviati correttamente a PHP. Il tentativo di farlo causerà un comportamento indefinito. Questo include (ma non è limitato a) la restituzione di tali strutture di dati dal modulo chiamato da {{#invoke:}} e passando tali strutture di dati come parametri alle funzioni di libreria Scribunto che sono implementati come callback in PHP.

Queste strutture di dati possono essere utilizzati liberamente all'interno di Lua, includendo i valori di ritorno dei moduli caricati con mw.loadData().

Writing Scribunto libraries

This information is useful to developers writing additional Scribunto libraries, whether for inclusion in Scribunto itself or for providing an interface for their own extensions.

A Scribunto library will generally consist of five parts:

  • The PHP portion of the library.
  • The Lua portion of the library.
  • The PHP portion of the test cases.
  • The Lua portion of the test cases.
  • The documentation.

Existing libraries serve as a good example.

Library

The PHP portion of the library is a class that must extend Scribunto_LuaLibraryBase. See the documentation for that class for implementation details. In the Scribunto extension, this file should be placed in engines/LuaCommon/NameLibrary.php, and a mapping added to Scribunto_LuaEngine::$libraryClasses. Other extensions should use the ScribuntoExternalLibraries hook. In either case, the key should match the Lua module name ("mw.name" for libraries in Scribunto, or "mw.ext.name" for extension libraries).

The Lua portion of the library sets up the table containing the functions that can be called from Lua modules. In the Scribunto extension, the file should be placed in engines/LuaCommon/lualib/mw.name.lua. This file should generally include boilerplate something like this:

local object = {}
local php

function object.setupInterface( options )
    -- Remove setup function
    object.setupInterface = nil

    -- Copy the PHP callbacks to a local variable, and remove the global
    php = mw_interface
    mw_interface = nil

    -- Do any other setup here

    -- Install into the mw global
    mw = mw or {}
    mw.ext = mw.ext or {}
    mw.ext.name = object

    -- Indicate that we're loaded
    package.loaded['mw.ext.name'] = object
end

return object

The module in engines/LuaCommon/lualib/libraryUtil.lua (load this with local util = require 'libraryUtil') contains some functions that may be helpful.

Be sure to run the Scribunto test cases with your library loaded, even if your library doesn't itself provide any test cases. The standard test cases include tests for things like libraries adding unexpected global variables. Also, if the library is loaded with PHP, any upvalues that its Lua functions have will not be reset between #invoke's. Care must be taken to ensure that modules can't abuse this to transfer information between #invoke's.

Test cases

The Scribunto extension includes a base class for test cases, Scribunto_LuaEngineTestBase, which will run the tests against both the LuaSandbox and LuaStandalone engines. The library's test case should extend this class, and should not override static function suite(). In the Scribunto extension, the test case should be in tests/engines/LuaCommon/NameLibraryTest.php and added to the array in ScribuntoHooks::unitTestsList() (in common/Hooks.php); extensions should add the test case in their own UnitTestsList hook function, probably conditional on whether $wgAutoloadClasses['Scribunto_LuaEngineTestBase'] is set.

Most of the time, all that is needed to make the test case is this:

class ClassNameTest extends Scribunto_LuaEngineTestBase {
    protected static $moduleName = 'ClassNameTest';

    function getTestModules() {
         return parent::getTestModules() + array(
             'ClassNameTest' => __DIR__ . '/ClassNameTests.lua';
         );
    }
}

This will load the file ClassNameTests.lua as if it were the page "Module:ClassNameTests", expecting it to return an object with the following properties:

  • count: Integer, number of tests
  • provide( n ): Function that returns three values: n, the name of test n, and a string that is the expected output for test n.
  • run( n ): Function that runs test n and returns one string.

If getTestModules() is declared as shown, "Module:TestFramework" is available which provides many useful helper methods. If this is used, ClassNameTests.lua would look something like this:

local testframework = require 'Module:TestFramework'

return testframework.getTestProvider( {
    -- Tests go here
} )

Each test is itself a table, with the following properties:

  • name: The name of the test.
  • func: The function to execute.
  • args: Optional table of arguments to pass to the function.
  • expect: Results to expect.
  • type: Optional "type" of the test, default is "Normal".

The type controls the format of expect and how func is called. Included types are:

  • Normal: expect is a table of return values, or a string if the test should raise an error. func is simply called.
  • Iterator: expect is a table of tables of return values. func is called as with an iterated for loop, and each iteration's return values are accumulated.
  • ToString: Like "Normal", except each return value is passed through tostring().

Test cases in another extension

There are (at least) two ways to run PHPUnit tests:

  1. Run phpunit against core, allowing the tests/phpunit/suites/ExtensionsTestSuite.php to find the extension's tests using the UnitTestsList hook. If your extension's test class names all contain a unique component (e.g. the extension's name), the --filter option may be used to run only your extension's tests.
  2. Run phpunit against the extension directory, where it will pick up any file ending in "Test.php".

Either of these will work fine if Scribunto is loaded in LocalSettings.php. And it is easy for method #1 to work if Scribunto is not loaded, as the UnitTestsList hook can easily be written to avoid returning the Scribunto test when $wgAutoloadClasses['Scribunto_LuaEngineTestBase'] is not set.

But Jenkins uses method #2. For Jenkins to properly run the tests, you will need to add Scribunto as a dependency for your extension. See Template:Gerrit for an example of how this is done.

If for some reason you need the tests to be able to run using method #2 without Scribunto loaded, one workaround is to add this check to the top of your unit test file:

if ( !isset( $GLOBALS['wgAutoloadClasses']['Scribunto_LuaEngineTestBase'] ) ) {
    return;
}

Documentation

Modules included in Scribunto should include documentation in the Scribunto libraries section above. Extension libraries should include documentation in a subpage of their own Extension page, and link to that documentation from #Extension libraries (mw.ext).

See also

License

This manual is derived from the Lua 5.1 reference manual, which is available under the MIT license.

Copyright © 1994–2012 Lua.org, PUC-Rio.

Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions:

The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software.

THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.

This derivative manual may also be copied under the terms of the same license.

Note
  1. 1,0 1,1 1,2 1,3 1,4 1,5 Non a Number
  2. 2,0 2,1 2,2 2,3 Termine coniato dall'informatico inglese Peter J. Landin per definire costrutti sintattici di un linguaggio di programmazione che non hanno effetto sulla funzionalità del linguaggio, ma ne rendono più facile ("dolce") l'uso per gli esseri umani. Vedi Zucchero sintattico
  3. 3,0 3,1 Memoria non più referenziata e liberata automaticamente. Vedi Garbage collection
  4. 4,0 4,1 In informatica, un tail call (chianmta di coda) è una chiamata di subroutine eseguito come l'azione finale di una procedura.
  5. L'insieme delle informazioni specifiche di una subroutine all'interno di un call stack è detto frame.
  6. 6,0 6,1 6,2 In informatica, un call stack è una zona di memoria di un programma, organizzata in forma di stack, nella quale sono immagazzinate le informazioni sulle subroutine attive in un dato momento (le subroutine attive sono quelle che sono state invocate ma la cui esecuzione non è terminata). Il termine stack o pila, in informatica, indica un tipo di dato astratto che viene usato in diversi contesti per riferirsi a strutture dati, le cui modalità d'accesso ai dati in essa contenuti seguono una modalità LIFO (Last In First Out), ovvero tale per cui i dati vengono estratti (letti) in ordine rigorosamente inverso rispetto a quello in cui sono stati inseriti (scritti).
  7. Un pezzo di software che ha la stessa funzione di un altro.
  8. Il tempo coordinato universale, conosciuto anche come tempo civile e abbreviato con la sigla UTC, è il fuso orario di riferimento da cui sono calcolati tutti gli altri fusi orari del mondo. Esso è derivato dal tempo medio di Greenwich.
  9. 9,0 9,1 9,2 9,3 9,4 9,5 9,6 Nella terminologia di codifica dei caratteri, un codepoint o codeposition è uno dei valori numerici che compongono lo spazio codice. Molti codepoint rappresentano caratteri singoli, ma possono anche avere altri significati, come indicazioni per la formattazione.
  10. Il termine offset, o slittamento, è usato per indicare la differenza rispetto ad un valore di riferimento.
  11. 11,0 11,1 11,2 Un no-op o nop, signifiva No Operation nessuna operazione, è un'istruzione che occupa una piccola quantità di spazio, ma non specifica alcuna operazione. Il processore del computer semplicemente si sposta sulla successiva istruzione sequenziale. Il no-op è incluso nella maggior parte dei linguaggi assembler. Può avere un'etichetta e può servire come segnaposto per un'istruzione utile da inserire successivamente durante lo sviluppo del codice.
  12. Autonimia
Collegamenti esterni