Skip to content

Data a persistence ​

JSON a soubory ​

Client / Server

lua
local encoded = Json.Encode({ enabled = true })
local value = Json.Decode(encoded)

Storage.WriteJson('data/state.json', value, true)
local state = Storage.ReadJson('data/state.json')
Storage.Delete('data/state.json')

Cesty ve storage jsou sandboxované na aktuální resource a omezené na JSON soubory. Pro autoritativní gameplay stav používejte server-side storage.

MySQL ​

Server

Nastavení enginu v server.cfg:

ini
sets mysql_connection_string "mysql://user:password@host:3306/database?charset=utf8mb4"
set mysql_slow_query_warning "500"

Dotazování přes callbacky:

lua
MySQL.query('SELECT id, title FROM quests WHERE steam_id = @steamId', {
  ['@steamId'] = steamId
}, function(rows)
  print('loaded ' .. tostring(#rows) .. ' quests')
end)

Nebo z managed coroutine:

lua
CreateThread(function()
  local row = MySQL.single.await(
    'SELECT title FROM profiles WHERE steam_id = @steamId',
    { ['@steamId'] = steamId }
  )

  if row then
    print(row.title)
  end
end)

Dostupné rodiny operací zahrnují query, single, scalar, insert, update, prepare, rawExecute, transaction a interaktivní transakce. Pending operace se při zastavení resource ruší.

Souběh inventáře ​

Server

Zápisy do inventáře mohou používat očekávanou revision pro odmítnutí zastaralých změn:

lua
local revision = Inventory.GetRevision(peerId)
local added = Inventory.AddItem(peerId, 'Coins', 5, 1, revision)

if not added then
  print('inventory changed or has no capacity')
end

Pro více změn použijte transaction:

lua
local revision = Inventory.GetRevision(peerId)
local transactionId = Inventory.BeginTransaction(peerId, revision)

if transactionId then
  local removed = Inventory.RemoveItem(peerId, 'Coins', 10)
  local added = Inventory.AddItem(peerId, 'SwordIron', 1)

  if removed and added then
    Inventory.CommitTransaction(transactionId)
  else
    Inventory.RollbackTransaction(transactionId)
  end
end

Inventory API podporuje také lookup itemů, přesuny slotů, split/merge stacků, update metadat, resize i synthetic server inventories. Kompletní signatury najdete v detailed native reference.

Lua resources pro Valheim postavené na server-authoritative runtime.