Skip to content

Data and Persistence

JSON and files

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')

Storage paths are sandboxed to the current resource and limited to JSON files. Use server-side storage for authoritative gameplay state.

MySQL

Server

Configure the engine in server.cfg:

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

Query with callbacks:

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

Or from a 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)

Available operation families include query, single, scalar, insert, update, prepare, rawExecute, transaction, and interactive transactions. Pending operations are cancelled when their resource stops.

Inventory concurrency

Server

Inventory writes can use an expected revision to reject stale mutations:

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

For multiple changes, use a 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 APIs also support item lookup, slot movement, stack split/merge, metadata updates, resize, and synthetic server inventories. See the detailed native reference for all signatures.

Lua resources for Valheim, built on a server-authoritative runtime.