The Battle for Wesnoth  1.13.4+dev
 All Classes Namespaces Files Functions Variables Typedefs Enumerations Enumerator Friends Macros Modules Pages
lua_pathfind_cost_calculator.hpp
Go to the documentation of this file.
1 #pragma once
2 #include "lua/lua.h"
3 #include "map/location.hpp"
4 #include "scripting/lua_api.hpp"
5 #include "pathfind/pathfind.hpp"
6 
7 /**
8  * Cost function object relying on a Lua function.
9  * @note The stack index of the Lua function must be valid each time the cost is computed.
10  */
12 {
14  int index;
15  /// @param i the stack position of the lua function to calculate the cost.
16  lua_pathfind_cost_calculator(lua_State *L_, int i): L(L_), index(i) {}
17  double cost(const map_location &loc, const double so_far) const
18  {
19  // Copy the user function and push the location and current cost.
20  lua_pushvalue(L, index);
21  lua_pushinteger(L, loc.x + 1);
22  lua_pushinteger(L, loc.y + 1);
23  lua_pushnumber(L, so_far);
24  // Execute the user function.
25  if (!luaW_pcall(L, 3, 1)) {
26  return 1.;
27  }
28  // Return a cost of at least 1 mp to avoid issues in pathfinder.
29  // (Condition is inverted to detect NaNs.)
30  double cost = lua_tonumber(L, -1);
31  lua_pop(L, 1);
32  return !(cost >= 1.) ? 1. : cost;
33  }
34 };
bool luaW_pcall(lua_State *L, int nArgs, int nRets, bool allow_wml_error)
Calls a Lua function stored below its nArgs arguments at the top of the stack.
Definition: lua_api.cpp:59
double cost(const map_location &loc, const double so_far) const
#define lua_tonumber(L, i)
Definition: lua.h:318
lua_pathfind_cost_calculator(lua_State *L_, int i)
#define lua_pop(L, n)
Definition: lua.h:322
LUA_API void lua_pushnumber(lua_State *L, lua_Number n)
Definition: lapi.cpp:467
Encapsulates the map of the game.
Definition: location.hpp:38
Cost function object relying on a Lua function.
size_t i
Definition: function.cpp:1057
LUA_API void lua_pushvalue(lua_State *L, int idx)
Definition: lapi.cpp:229
LUA_API void lua_pushinteger(lua_State *L, lua_Integer n)
Definition: lapi.cpp:477
This module contains various pathfinding functions and utilities.