English 中文(简体)
字面上插图的传呼方法
原标题:Call string method on string literal
  • 时间:2024-02-09 01:33:28
  •  标签:
  • lua

If I have a variable of string type, I can use the : syntax to call functions on the string metatable:

local s = "%d"
print(s:format(s:byte(1)))  -- 37

但是,这并没有说明字面:

print("%d":format("%d":byte(1)))
--  )  expected near  : 

Why? Is there a trick to make this work?

问题回答

2. 随母体对面字进行回顾:

print(("%d"):format(("%d"):byte(1)))

https://www.lua.org/manual/5.4/manual.html

9 – The Complete Syntax of Lua

...
var ::=  Name | prefixexp ‘[’ exp ‘]’ | prefixexp ‘.’ Name 
...
prefixexp ::= var | functioncall | ‘(’ exp ‘)’
functioncall ::=  prefixexp args | prefixexp ‘:’ Name args
...

Basically:

  • A "method" functioncall is made of four parts: prefixexp, the colon, the name of the method, and its arguments.
  • A prefixexp can be either a functioncall itself, an exp wrapped inside parenthesis, or a var.
  • A var can be an identifier, or its indexed/dotted counterpart.

This effectively disallow using the shorthand :method syntax on all kinds of literal expressions, not just strings. That said, these are all invalid syntax:

nil:has_no_method()
true:or_false()
2:too()
[[long strings]]:same_thing()
function() end:really()
{}:h_yes_definitely()




相关问题
Wrapping a Lua object for use in C++ with SWIG

Currently I know how to have C++ objects instantiated and passed around in Lua using SWIG bindings, what I need is the reverse. I am using Lua & C++ & SWIG. I have interfaces in C++ and ...

Can t lua_resume after async_wait?

I have some lua script that have some long running task like getting a web page so I make it yield then the C code handle get page job async, so the thread free to do other job and after a specify ...

How to remove a lua table entry by its key?

I have a lua table that I use as a hashmap, ie with string keys : local map = { foo = 1, bar = 2 } I would like to "pop" an element of this table identified by its key. There is a table.remove() ...

Lua plain string.gsub

I ve hit s small block with string parsing. I have a string like: footage/down/temp/cars_[100]_upper/cars_[100]_upper.exr and I m having difficulty using gsub to delete a portion of the string. ...

why do i get "attempt to call global require (a nil value)"?

I have 3 lua files, Init.lua, FreeCamera.lua and Camera.lua , init.lua calls require "Core.Camera.FreeCamera" Free Camera: module(...) require "Core.Camera.Camera" local M = {} FreeCamera = M M ...

热门标签