AskOverflow.Dev

AskOverflow.Dev Logo AskOverflow.Dev Logo

AskOverflow.Dev Navigation

  • Início
  • system&network
  • Ubuntu
  • Unix
  • DBA
  • Computer
  • Coding
  • LangChain

Mobile menu

Close
  • Início
  • system&network
    • Recentes
    • Highest score
    • tags
  • Ubuntu
    • Recentes
    • Highest score
    • tags
  • Unix
    • Recentes
    • tags
  • DBA
    • Recentes
    • tags
  • Computer
    • Recentes
    • tags
  • Coding
    • Recentes
    • tags
Início / coding / Perguntas / 77023880
Accepted
Jepessen
Jepessen
Asked: 2023-09-01 22:20:19 +0800 CST2023-09-01 22:20:19 +0800 CST 2023-09-01 22:20:19 +0800 CST

Leia a chave e os valores de um script lua aninhado em C/C++

  • 772

Tenho o seguinte script lua, no qual uso uma função C++ que precisa ler chaves e valores de uma tabela aninhada:

local scenariolist = {
   scenarios = {
      'scenario1',
      'scenario3',
      'scenario2'
   },
   result = true,
   message = 'test message'
}

my.sendfromscenariolist(scenariolist)

Esta é minha função C++ que é executada ao chamar sendfromscenariolist:

int ScenarioFunction(lua_State* L) {
  int nargs = lua_gettop(L);
  if (nargs != 1) {
    return 0;
  }
  int type = lua_type(L, 1);
  if (type != LUA_TTABLE) {
    return 0;
  }
  ParseScenarioTable(L);
  return 0;
}


void ParseScenarioTable(lua_State* L) {

  lua_pushnil(L);
  while (lua_next(L, -2) != 0) {
    if (lua_istable(L, -1)) {
      ParseScenarioTable(L);
      std::cout << "Key: " << "key" << ", Value is table" << std::endl;
    }
    else if (lua_isstring(L, -1)) {
      std::string x = lua_tostring(L, -1);
      std::cout << "Key: " << "key" << ", Value: " << x << std::endl;
      int i = 0;
    }
    else if (lua_isboolean(L, -1)) {
      bool x = lua_toboolean(L, -1);
      int i = 0;
      std::cout << "Key: " << "key" << ", Value: " << x << std::endl;
    }
    lua_pop(L, 1);
  }
}

Esta função lê apenas valores e funciona, quando executo no console obtenho:

Key: key, Value: 1
Key: key, Value: scenario1
Key: key, Value: scenario3
Key: key, Value: scenario2
Key: key, Value is table
Key: key, Value: test message

O problema é que não consigo ler também chaves de elementos de tabela aninhados. Eu mudei meu código com isso:

int ScenarioFunction(lua_State* L) {
  int nargs = lua_gettop(L);
  if (nargs != 1) {
    return 0;
  }
  int type = lua_type(L, 1);
  if (type != LUA_TTABLE) {
    return 0;
  }
  ParseScenarioTable(L);
  return 0;
}


void ParseScenarioTable(lua_State* L) {

  lua_pushnil(L);
  while (lua_next(L, -2) != 0) {
    if (lua_istable(L, -1)) {
      std::string key = lua_tostring(L, -2);
      ParseScenarioTable(L);
      std::cout << "Key: " << key << ", Value is table" << std::endl;
    }
    else if (lua_isstring(L, -1)) {
      std::string key = lua_tostring(L, -2);
      std::string x = lua_tostring(L, -1);
      std::cout << "Key: " << key << ", Value: " << x << std::endl;
      int i = 0;
    }
    else if (lua_isboolean(L, -1)) {
      std::string key = lua_tostring(L, -2);
      bool x = lua_toboolean(L, -1);
      int i = 0;
      std::cout << "Key: " << key << ", Value: " << x << std::endl;
    }
    lua_pop(L, 1);
  }
}

Mas se eu tentar ler as chaves, o programa irá quebrar e recebo um erro: Esta é a saída do meu programa:

Key: result, Value: 1
Key: 1, Value: scenario1
[2023-09-01 16:17:03.391093][error]: Error when running the script. Error is: invalid key to 'next'

onde invalid key to 'next'está a string de erro de lua.

O que estou fazendo de errado? Como posso ler chaves e valores?

c++
  • 1 1 respostas
  • 19 Views

1 respostas

  • Voted
  1. Best Answer
    ESkri
    2023-09-01T23:15:34+08:002023-09-01T23:15:34+08:00

    O problema está aqui:

    std::string key = lua_tostring(L, -2);
    

    O lua_tostringmodifica seu argumento: ele substitui number 1por string "1"no índice da pilha da API -2, portanto, o seguinte lua_nextnão pode continuar percorrendo a tabela, pois recebe uma chave não existente "1"em vez de existente 1.
    Este comportamento está descrito no manual .

    Solução:
    crie um slot de pilha temporário adicional para o valor a ser modificado por lua_tostring.
    Substituir

    std::string key = lua_tostring(L, -2);
    

    com

    lua_pushvalue(L, -2);
    std::string key = lua_tostring(L, -1);
    lua_pop(L, 1);
    
    • 1

relate perguntas

  • Por que os compiladores perdem a vetorização aqui?

  • Erro de compilação usando CMake com biblioteca [fechada]

  • Erro lançado toda vez que tento executar o premake

  • Como criar um tipo de octeto semelhante a std::byte em C++?

  • Somente operações bit a bit para std::byte em C++ 17?

Sidebar

Stats

  • Perguntas 205573
  • respostas 270741
  • best respostas 135370
  • utilizador 68524
  • Highest score
  • respostas
  • Marko Smith

    destaque o código em HTML usando <font color="#xxx">

    • 2 respostas
  • Marko Smith

    Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}?

    • 1 respostas
  • Marko Smith

    Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)?

    • 2 respostas
  • Marko Smith

    Por que as compreensões de lista criam uma função internamente?

    • 1 respostas
  • Marko Smith

    Estou tentando fazer o jogo pacman usando apenas o módulo Turtle Random e Math

    • 1 respostas
  • Marko Smith

    java.lang.NoSuchMethodError: 'void org.openqa.selenium.remote.http.ClientConfig.<init>(java.net.URI, java.time.Duration, java.time.Duratio

    • 3 respostas
  • Marko Smith

    Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)?

    • 4 respostas
  • Marko Smith

    Por que o construtor de uma variável global não é chamado em uma biblioteca?

    • 1 respostas
  • Marko Smith

    Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto?

    • 1 respostas
  • Marko Smith

    Somente operações bit a bit para std::byte em C++ 17?

    • 1 respostas
  • Martin Hope
    fbrereto Por que a resolução de sobrecarga prefere std::nullptr_t a uma classe ao passar {}? 2023-12-21 00:31:04 +0800 CST
  • Martin Hope
    比尔盖子 Você pode usar uma lista de inicialização com chaves como argumento de modelo (padrão)? 2023-12-17 10:02:06 +0800 CST
  • Martin Hope
    Amir reza Riahi Por que as compreensões de lista criam uma função internamente? 2023-11-16 20:53:19 +0800 CST
  • Martin Hope
    Michael A formato fmt %H:%M:%S sem decimais 2023-11-11 01:13:05 +0800 CST
  • Martin Hope
    God I Hate Python std::views::filter do C++20 não filtrando a visualização corretamente 2023-08-27 18:40:35 +0800 CST
  • Martin Hope
    LiDa Cute Por que 'char -> int' é promoção, mas 'char -> short' é conversão (mas não promoção)? 2023-08-24 20:46:59 +0800 CST
  • Martin Hope
    jabaa Por que o construtor de uma variável global não é chamado em uma biblioteca? 2023-08-18 07:15:20 +0800 CST
  • Martin Hope
    Panagiotis Syskakis Comportamento inconsistente de std::common_reference_with em tuplas. Qual é correto? 2023-08-17 21:24:06 +0800 CST
  • Martin Hope
    Alex Guteniev Por que os compiladores perdem a vetorização aqui? 2023-08-17 18:58:07 +0800 CST
  • Martin Hope
    wimalopaan Somente operações bit a bit para std::byte em C++ 17? 2023-08-17 17:13:58 +0800 CST

Hot tag

python javascript c++ c# java typescript sql reactjs html

Explore

  • Início
  • Perguntas
    • Recentes
    • Highest score
  • tag
  • help

Footer

AskOverflow.Dev

About Us

  • About Us
  • Contact Us

Legal Stuff

  • Privacy Policy

Language

  • Pt
  • Server
  • Unix

© 2023 AskOverflow.DEV All Rights Reserve