1

There is a token.set_char but no token.get_char. Starting from

\chardef\MyNumber=1

I can change the value with

\directlua{
  token.set_char('MyNumber', 421)
}

and retrieve the value on the TeX side

\the\MyNumber

but how to retrieve the value on the lua side?

I have one solution in mind but it is not satisfying: with tex.runtoks, lua can ask tex to copy MyNumber to a dedicated count register, and then retrieve the value using tex.count.

0

2 Answers 2

3

The fastest way is to extract the value from the token using .index

\directlua{
  local char_given = token.command_id'char_given'
  local function get_char(name)
    local tok = token.create(name)
    if not (tok.command == char_given) then
      error'Not a chardef'
    end
    return tok.index
  end
  token.set_char('MyNumber', 421)
  local restored = get_char'MyNumber'
}
\bye

but if you want it to be more generic and also e.g. accepts count registers you can also add the token to the input stream and than scan it as a number:

  local function get_char(name)
    token.put_next(token.create(name))
    return token.scan_int()
  end
  token.set_char('MyNumber', 421)
  local restored = get_char'MyNumber'
}
\bye
2
  • I thought it's mode (last time I tested)... (luatex - Querying the state of a boolean from lua - TeX - LaTeX Stack Exchange)
    – user202729
    Commented Jun 2, 2022 at 13:55
  • @user202729 index is basically the new version of mode. For most commands they are the same, but for some mode has some weird offsets which index automatically takes care of. So except if you want to be compatible with old LuaTeX versions which didn't have index yet, it's almost always better to use index. (Also looking forward index is compatible with LuaMetaTeX which removed mode) Commented Jun 2, 2022 at 14:51
2

If you are using \directlua (i.e. no external .lua file) then you can get the value from TeX world to the Lua world by expanding it inside the Lua code, because \directlua expands its argument before the Lua code is read. For example

\directlua{... ... myvariable = \the\MyNumber ... ...}
1
  • More precisely, this very simple solution assumes that one wants the value of \MyNumber at the time LuaTeX parses the \directlua argument and not at the time the assignment instruction myvariable=... is executed. +1 Commented Jun 3, 2022 at 11:29

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .